﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebSite.App_Data;
using WebSite.App_Code;
using Excel = Microsoft.Office.Interop.Excel;
using System.Web.Configuration;
using WebSite.Models;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace WebSite.App_Code
{
    public enum DBOperationResult
    {
            /// <summary> 操作成功 </summary>
        Success = 0
            /// <summary> 新建成功 </summary>
        ,Insert_Success = 1000
            /// <summary> 更新成功 </summary>
        ,Update_Success = 2000
            /// <summary> 更新失败，记录不存在 </summary>
        ,Update_Fail_NoRecord = -2001
            /// <summary> 删除成功 </summary>
        ,Delete_Success = 3000
            /// <summary> 删除失败，记录不存在 </summary>
        ,Delete_Fail_NoRecord = -3001
            /// <summary> 删除失败, 存在子组织 </summary>
        ,Delete_Fail_HasChildDepartment = -3002
            /// <summary> 导入成功 </summary>
        ,Import_Success = 4000
            /// <summary> 导入失败,项目类别不正确 </summary>
        ,Import_Fail_ProjectCategory_NoMatch = -4001
            /// <summary> 导入失败,项目类型不正确 </summary>
        , Import_Fail_ProjectType_NoMatch = -4002
            /// <summary> 导入失败,编制单位不正确 </summary>
        , Import_Fail_Department_NoMatch = -4003
            /// <summary> 导入提示，项目负责人变更 </summary>
        , Import_Alert_ProjectPICChange = 4004
    }

    public enum Role
    {
        /// <summary> 一般用户 </summary>
        NORMAL = 1,
        /// <summary> 主管 </summary>
        PIC = 2,
        /// <summary> 所主管 </summary>
        MPIC = 3,
        /// <summary> 财务审核 </summary>
        AA = 4,
        /// <summary> 管理员 </summary>
        MGR = 5,
        /// <summary> 出纳 </summary>
        TELLER = 6,
    }

    public enum L_PayStatus
    {
        /// <summary> 保存 </summary>
        Save = 0,
        /// <summary> 等待出纳确认 </summary>
        Pending = 1,
        /// <summary> 现金已确认，银行未确认 </summary>
        CashConfirm = 2,
        /// <summary> 现金未确认，银行已确认 </summary>
        BankConfirm = 3,
        /// <summary> 完成 </summary>
        Complete = 4,
        /// <summary> 作废 </summary>
        Cancel = 5,
        /// <summary> 红冲 </summary>
        Reverse = 6,
    }

    public enum L_SubRoleType
    {
        /// <summary> 自定义部门 </summary>
        Department = 0,
        /// <summary> 本部门 </summary>
        SelfDepartment = 1,
        /// <summary> 全部门 </summary>
        AllDepartment = 2,
        /// <summary> 本人 </summary>
        Self = 3,
    }

    public enum L_CheckType
    {
        /// <summary> By部门 </summary>
        Department = 0,
        /// <summary> By人 </summary>
        User = 1,
    }

    public enum L_BudgetStatus
    {
        /// <summary> 开放提交 </summary>
        Open = 0,
        /// <summary> 审核中 </summary>
        Approve = 20,
        /// <summary> 启用 </summary>
        Use = 40,
        /// <summary> 调整中 </summary>
        Adjust = 60,
        /// <summary> 完成 </summary>
        Complete = 80,
        /// <summary> 关闭 </summary>
        Close = 100,
        /// <summary> 已提交 </summary>
        Upload = 10,
    }

    public enum L_ActionType
    {
        /// <summary> 查询 </summary>
        Query = 10,
        /// <summary> 上传 </summary>
        Upload = 20,
        /// <summary> 删除 </summary>
        Delete = 30,
        /// <summary> 审批 </summary>
        Approve = 40,
        /// <summary> 修改 </summary>
        Modify = 50,
        /// <summary> 调整 </summary>
        Adjust = 60,
        /// <summary> 结转 </summary>
        Transfer = 70,
        /// <summary> 发起支付 </summary>
        Paid = 80,
        /// <summary> 变更状态 </summary>
        ChangeStatus = 90,
    }

    public enum L_LogType
    {
        NULL = 0,
        /// <summary> 主数据-用户-新建 </summary>
        MD_User_Insert = 10101,
        /// <summary> 主数据-用户-修改 </summary>
        MD_User_Update = 10102,
        /// <summary> 主数据-用户-无效 </summary>
        MD_User_Disable = 10103,
        /// <summary> 主数据-用户-启用 </summary>
        MD_User_Enable = 10104,
        /// <summary> 主数据-用户-修改权限 </summary>
        MD_User_ChangeRole = 10105,
        /// <summary> 主数据-用户-重置密码 </summary>
        MD_User_ResetPwd = 10106,
        /// <summary> 主数据-用户-修改密码 </summary>
        MD_User_ChangePwd = 10107,

        /// <summary> 主数据-组织-新建 </summary>
        MD_Department_Insert = 10201,
        /// <summary> 主数据-组织-修改 </summary>
        MD_Department_Update = 10202,
        /// <summary> 主数据-组织-无效 </summary>
        MD_Department_Disable = 10203,
        /// <summary> 主数据-组织-启用 </summary>
        MD_Department_Enable = 10204,
        /// <summary> 主数据-组织-上移 </summary>
        MD_Department_Up = 10205,
        /// <summary> 主数据-组织-下移 </summary>
        MD_Department_Down = 10206,

        /// <summary> 主数据-费用科目-新建 </summary>
        MD_ExpenseCategory_Insert = 10301,
        /// <summary> 主数据-费用科目-修改 </summary>
        MD_ExpenseCategory_Update = 10302,
        /// <summary> 主数据-费用科目-无效 </summary>
        MD_ExpenseCategory_Disable = 10303,
        /// <summary> 主数据-费用科目-启用 </summary>
        MD_ExpenseCategory_Enable = 10304,

        /// <summary> 主数据-项目-删除 </summary>
        MD_Project_Delete = 10401,

        /// <summary> 预算控制-初始化项目 </summary>
        B_InitProjec = 20101,
        /// <summary> 预算控制-初始化雨伞 </summary>
        B_InitBudegt = 20102,
        /// <summary> 预算控制-预算提交 </summary>
        B_Upload = 20103,
        /// <summary> 预算控制-预算变更 </summary>
        B_Update = 20304,
        /// <summary> 预算控制-预算审核 </summary>
        B_Approve = 20305,
        /// <summary> 预算控制-放弃审核 </summary>
        B_Rollback_Approve = 20306,
        /// <summary> 预算调整-关闭预算 </summary>
        B_Close = 20307,
        /// <summary> 预算调整-关闭变调整 </summary>
        B_CloseToAdjust = 20308,
        /// <summary> 预算调整-关闭变完成 </summary>
        B_CloseToComplete = 20309,
        /// <summary> 预算调整-关闭变开发提交 </summary>
        B_CloseToOpen = 20310,

        /// <summary> 经费审核结算-保存 </summary>
        P_Save = 30101,
        /// <summary> 经费审核结算-提交 </summary>
        P_Submit = 30102,

        /// <summary> 登录 </summary>
        COM_Login = 20101,

        /// <summary> 其他 </summary>
        Other = 99999,
    }

    public enum L_PageEvent
    {
        Default = 0,
        /// <summary> 系主数据管理 > 人员 [查询] </summary>
        MD_User_Query = 03010101,
        /// <summary> 系主数据管理 > 人员 [修改] </summary>
        MD_User_Upadte = 03010102,
        /// <summary> 系主数据管理 > 人员 [添加] </summary>
        MD_User_Insert = 03010103,
        /// <summary> 系主数据管理 > 人员 [删除] </summary>
        MD_User_Delete = 03010104,
        /// <summary> 系主数据管理 > 人员 [启用] </summary>
        MD_User_Enable = 03010105,
        /// <summary> 系主数据管理 > 人员 [修改密码] </summary>
        MD_User_ChangePwd = 03010106,
        /// <summary> 系主数据管理 > 人员 [更新角色] </summary>
        MD_User_UpdateRole = 03010107,
        /// <summary> 系主数据管理 > 人员 [重置密码] </summary>
        MD_User_ResetPwd = 03010108,

        /// <summary> 系主数据管理 > 项目 [查询] </summary>
        MD_Project_Query = 03010401,
        /// <summary> 系主数据管理 > 项目 [删除] </summary>
        MD_Project_Delete = 03010404,

        /// <summary> 预算审核 > 待审核预算一览 [查询] </summary>
        B_AppoverList_Qury = 01020101,
        /// <summary> 预算审核 > 待审核预算一览 [审核模板导出] </summary>
        B_AppoverList_Export = 01020102,
        /// <summary> 预算审核 > 待审核预算一览 [审核模板导入] </summary>
        B_AppoverList_Import = 01020103,
        /// <summary> 预算审核 > 待审核预算一览 [审核模板导入确认] </summary>
        B_AppoverList_ImportConfirm = 01020104,
        /// <summary> 预算审核 > 待审核预算一览 [批量放弃审核] </summary>
        B_AppoverList_BatchReturn = 01020105,
        /// <summary> 预算审核 > 待审核预算一览 [批量审核] </summary>
        B_AppoverList_BatchAppove = 01020106,

        /// <summary> 预算审核 > 预算状态调整 [查询] </summary>
        B_AdjustList_Qury = 01060001,
        /// <summary> 预算审核 > 预算状态调整 [关闭] </summary>
        B_AdjustList_Close = 01060002,
        /// <summary> 预算审核 > 预算状态调整 [关闭->调整] </summary>
        B_AdjustList_CloseToAdjust = 01060003,
        /// <summary> 预算审核 > 预算状态调整 [关闭->完成] </summary>
        B_AdjustList_CloseToComplete = 01060004,
        /// <summary> 预算审核 > 预算状态调整 [关闭->开发提交] </summary>
        B_AdjustList_CloseToOpen = 01060005,

        /// <summary> 收支核算申请 > 经费审核结算单 [保存] </summary>
        P_PaySubmit_Save = 03010101,
        /// <summary> 收支核算申请 > 经费审核结算单 [提交] </summary>
        P_PaySubmit_Submit = 03010102,
        /// <summary> 收支核算申请 > 经费审核结算单 [打印] </summary>
        P_PaySubmit_Print = 03010103,
        /// <summary> 收支核算申请 > 经费审核结算单 [Add Item] </summary>
        P_PaySubmit_AddItem = 03010104,
        /// <summary> 收支核算申请 > 经费审核结算单 [Delete Item] </summary>
        P_PaySubmit_DeleteItem = 03010105,
        /// <summary> 收支核算申请 > 经费审核结算单 [Select AccountCode Detail] </summary>
        P_PaySubmit_SelAccountCodeDetail = 03010106,
    }

    public enum L_BudgetTableType
    {
        Query = 1,
        AppoverList = 2,
        AdjustList = 3,
    }

    public enum L_BudgetDetailPageType
    {
        ForShow = 1,
        ForAppove = 2,
    }

    public enum L_AccountType
    {
        NA = 0,
        /// <summary>预算</summary>
        Budget = 1,
        /// <summary>资产</summary>
        Asset = 2,
    }

    public enum L_PayCatrgory
    {
        /// <summary>现金付</summary>
        PayCash = 1,
        /// <summary>银行付</summary>
        PayBank = 2,
        /// <summary>转账</summary>
        Transfer = 3,
        /// <summary>POS</summary>
        Pos = 4,
        /// <summary>收款-现金</summary>
        CollectCash = 5,
        /// <summary>收款-银行</summary>
        CollectBank = 6,
        /// <summary>还款-现金</summary>
        RepayCash = 7,
        /// <summary>还款-银行</summary>
        RepayBank = 8,
    }

    public enum L_Page
    {
        /// <summary>[37] 按经费查询</summary>
        PayQuery = 37,
        /// <summary>[31] 待提交单据一览</summary>
        PaySubmitList = 31,
        /// <summary>[35] 待确认单据一览</summary>
        PayConfirmList = 35,
    }

    #region Item.Department

    public class DepartmentItem
    {
        public DepartmentItem()
        {
            Department = new md_Department();
            ParentDepartment = new md_Department();
            Level = new md_DepartmentLevel();
        }

        public IEnumerable<SelectListItem> LevelSource { get; set; }

        public IEnumerable<SelectListItem> ParentDepartmentSource { get; set; }

        public md_DepartmentLevel Level { get; set; }

        public md_Department Department { get; set; }

        public md_Department ParentDepartment { get; set; }
    }

    #endregion

    #region Item.WebUser

    public class WebUserItem
    {
        public WebUserItem()
        {
            User = new md_User();
            Department = new DepartmentItem();
        }

        public md_User User { get; set; }
        
        public DepartmentItem Department { get; set; }

        public IEnumerable<SelectListItem> DepartmentSource { get; set; }

        public List<SelectListItem> RoleList { get; set; }
    }

    #endregion

    #region Item.ExpenseCategory

    public class ExpenseCategoryItem
    {
        public ExpenseCategoryItem()
        {
            Category = new md_ExpenseCategory();
            Group = new md_ExpenseCategoryGroup();
            Parent = new md_ExpenseCategory();
        }

        public md_ExpenseCategory Category { get; set; }

        public md_ExpenseCategory Parent { get; set; }

        public md_ExpenseCategoryGroup Group { get; set; }

        public IEnumerable<SelectListItem> ParentSource { get; set; }

        public IEnumerable<SelectListItem> GroupSource { get; set; }        
    }

    #endregion

    #region Item.Role

    public class RoleItem_AuthElement
    {
        public RoleItem_AuthElement()
        {
            CanQuery = false;
            CanModify = false;
            CanApprove = false;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 上传 </summary>
        public Boolean CanModify { get; set; }
        
        /// <summary> 审批 </summary>
        public Boolean CanApprove { get; set; }
    }

    public class SubRole_Open
    {
        public SubRole_Open()
        {
            CanQuery = false;
            CanUpload = false;
            CanApprove = false;
            CanChangeStatus = false;
        }

        public SubRole_Open(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanUpload = Convert.ToBoolean(Temp & 2);
                CanApprove = Convert.ToBoolean(Temp & 4);
                CanChangeStatus = Convert.ToBoolean(Temp & 8);
            }
            else
            {
                CanQuery = false;
                CanUpload = false;
                CanApprove = false;
                CanChangeStatus = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanUpload ? 1 : 0) * 2;
            Temp += (CanApprove ? 1 : 0) * 4;
            Temp += (CanChangeStatus ? 1 : 0) * 8;

            return Temp.ToString();
        }

        public void Union(SubRole_Open O)
        {
            this.CanApprove = this.CanApprove || O.CanApprove;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanUpload = this.CanUpload || O.CanUpload;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 上传 </summary>
        public Boolean CanUpload { get; set; }

        /// <summary> 审批 </summary>
        public Boolean CanApprove { get; set; }

        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_Upload
    {
        public SubRole_Upload()
        {
            CanQuery = false;
            CanUpload = false;
            CanDelete = false;
            CanApprove = false;
            CanChangeStatus = false;
        }

        public SubRole_Upload(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanUpload = Convert.ToBoolean(Temp & 2);
                CanDelete = Convert.ToBoolean(Temp & 4);
                CanApprove = Convert.ToBoolean(Temp & 8);
                CanChangeStatus = Convert.ToBoolean(Temp & 16);
            }
            else
            {
                CanQuery = false;
                CanUpload = false;
                CanDelete = false;
                CanApprove = false;
                CanChangeStatus = false;
            }
        }

        public void Union(SubRole_Upload O)
        {
            this.CanApprove = this.CanApprove || O.CanApprove;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanUpload = this.CanUpload || O.CanUpload;
            this.CanDelete = this .CanDelete || O.CanDelete;
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanUpload ? 1 : 0) * 2;
            Temp += (CanDelete ? 1 : 0) * 4;
            Temp += (CanApprove ? 1 : 0) * 8;
            Temp += (CanChangeStatus ? 1 : 0) * 16;

            return Temp.ToString();
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 上传 </summary>
        public Boolean CanUpload { get; set; }

        /// <summary> 删除 </summary>
        public Boolean CanDelete { get; set; }

        /// <summary> 审批 </summary>
        public Boolean CanApprove { get; set; }

        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_Approve
    {
        public SubRole_Approve()
        {
            CanQuery = false;
            CanApprove = false;
            CanModify = false;
            CanChangeStatus = false;
        }

        public SubRole_Approve(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanApprove = Convert.ToBoolean(Temp & 2);
                CanModify = Convert.ToBoolean(Temp & 4);
                CanChangeStatus = Convert.ToBoolean(Temp & 8);
            }
            else
            {
                CanQuery = false;
                CanApprove = false;
                CanModify = false;
                CanChangeStatus = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanApprove ? 1 : 0) * 2;
            Temp += (CanModify ? 1 : 0) * 4;
            Temp += (CanChangeStatus ? 1 : 0) * 8;

            return Temp.ToString();
        }

        public void Union(SubRole_Approve O)
        {
            this.CanApprove = this.CanApprove || O.CanApprove;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanModify = this.CanModify || O.CanModify;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 审批 </summary>
        public Boolean CanApprove { get; set; }

        /// <summary> 修改 </summary>
        public Boolean CanModify { get; set; }

        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_Use
    {
        public SubRole_Use()
        {
            CanQuery = false;
            CanAdjust = false;
            CanTransfer = false;
            CanPaid = false;
        }

        public SubRole_Use(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanAdjust = Convert.ToBoolean(Temp & 2);
                CanTransfer = Convert.ToBoolean(Temp & 4);
                CanPaid = Convert.ToBoolean(Temp & 8);
            }
            else
            {
                CanQuery = false;
                CanAdjust = false;
                CanTransfer = false;
                CanPaid = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanAdjust ? 1 : 0) * 2;
            Temp += (CanTransfer ? 1 : 0) * 4;
            Temp += (CanPaid ? 1 : 0) * 8;

            return Temp.ToString();
        }

        public void Union(SubRole_Use O)
        {
            this.CanAdjust = this.CanAdjust || O.CanAdjust;
            this.CanTransfer = this.CanTransfer || O.CanTransfer;
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanPaid = this.CanPaid || O.CanPaid;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }
        
        /// <summary> 发起调整 </summary>
        public Boolean CanAdjust { get; set; }

        /// <summary> 结转 </summary>
        public Boolean CanTransfer { get; set; }

        /// <summary> 发起支付 </summary>
        public Boolean CanPaid { get; set; }
    }

    public class SubRole_Adjust
    {
        public SubRole_Adjust()
        {
            CanQuery = false;
            CanUpload = false;
            CanDelete = false;
            CanApprove = false;
            CanChangeStatus = false;
        }

        public SubRole_Adjust(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanUpload = Convert.ToBoolean(Temp & 2);
                CanDelete = Convert.ToBoolean(Temp & 4);
                CanApprove = Convert.ToBoolean(Temp & 8);
                CanChangeStatus = Convert.ToBoolean(Temp & 16);
            }
            else
            {
                CanQuery = false;
                CanUpload = false;
                CanDelete = false;
                CanApprove = false;
                CanChangeStatus = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanUpload ? 1 : 0) * 2;
            Temp += (CanDelete ? 1 : 0) * 4;
            Temp += (CanApprove ? 1 : 0) * 8;
            Temp += (CanChangeStatus ? 1 : 0) * 16;

            return Temp.ToString();
        }

        public void Union(SubRole_Adjust O)
        {
            this.CanUpload = this.CanUpload || O.CanUpload;
            this.CanDelete = this.CanDelete || O.CanDelete;
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanApprove = this.CanApprove || O.CanApprove;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 上传 </summary>
        public Boolean CanUpload { get; set; }

        /// <summary> 删除 </summary>
        public Boolean CanDelete { get; set; }
        
        /// <summary> 审批 </summary>
        public Boolean CanApprove { get; set; }
        
        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_Complete
    {
        public SubRole_Complete()
        {
            CanQuery = false;
            CanChangeStatus = false;
        }

        public SubRole_Complete(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanChangeStatus = Convert.ToBoolean(Temp & 2);
            }
            else
            {
                CanQuery = false;
                CanChangeStatus = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanChangeStatus ? 1 : 0) * 2;

            return Temp.ToString();
        }

        public void Union(SubRole_Complete O)
        {
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_Close
    {
        public SubRole_Close()
        {
            CanQuery = false;
            CanChangeStatus = false;
        }

        public SubRole_Close(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
                CanChangeStatus = Convert.ToBoolean(Temp & 2);
            }
            else
            {
                CanQuery = false;
                CanChangeStatus = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            Temp += (CanChangeStatus ? 1 : 0) * 2;

            return Temp.ToString();
        }

        public void Union(SubRole_Close O)
        {
            this.CanQuery = this.CanQuery || O.CanQuery;
            this.CanChangeStatus = this.CanChangeStatus || O.CanChangeStatus;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }

        /// <summary> 变更状态 </summary>
        public Boolean CanChangeStatus { get; set; }
    }

    public class SubRole_History
    {
        public SubRole_History()
        {
            CanQuery = false;
        }

        public SubRole_History(String V)
        {
            Int32 Temp = 0;

            if (Int32.TryParse(V, out Temp))
            {
                CanQuery = Convert.ToBoolean(Temp & 1);
            }
            else
            {
                CanQuery = false;
            }
        }

        public override string ToString()
        {
            Int32 Temp = 0;

            Temp += (CanQuery ? 1 : 0) * 1;
            
            return Temp.ToString();
        }

        public void Union(SubRole_History O)
        {
            this.CanQuery = this.CanQuery || O.CanQuery;
        }

        /// <summary> 查询 </summary>
        public Boolean CanQuery { get; set; }
    }

    public class SubRoleItem
    {
        public SubRoleItem()
        {
            OpenAuth = new SubRole_Open();
            UploadAuth = new SubRole_Upload();
            AdjustAuth = new SubRole_Adjust();
            AuditAuth = new SubRole_Approve();
            InUseAuth = new SubRole_Use();
            CompleteAuth = new SubRole_Complete();
            CloseAuth = new SubRole_Close();
            HistoryAuth = new SubRole_History();
            Name = String.Empty;
            Department = new md_Department();
            ProjectCtegory = new list_ProjectCategory();
            Type = L_SubRoleType.Department;
            OrderID = 0;
            Own = new md_User();
        }

        public Int32 OrderID { get; set; }

        public String Name { get; set; }

        public L_SubRoleType Type { get; set; } 

        public md_Department Department { get; set; }

        public md_User Own { get; set; }
                
        public list_ProjectCategory ProjectCtegory { get; set; }

        public List<SelectListItem> ProjectCtegorySource { get; set; }

        public List<SelectListItem> DepartmentSource { get; set; }

        /// <summary> 开放提交：权限 </summary>
        public SubRole_Open OpenAuth { get; set; }

        /// <summary> 已提交：权限 </summary>
        public SubRole_Upload UploadAuth { get; set; }

        /// <summary> 审核中：权限 </summary>
        public SubRole_Approve AuditAuth { get; set; }

        /// <summary> 启用：权限 </summary>
        public SubRole_Use InUseAuth { get; set; }

        /// <summary> 调整中：权限 </summary>
        public SubRole_Adjust AdjustAuth { get; set; }

        /// <summary> 完成：权限 </summary>
        public SubRole_Complete CompleteAuth { get; set; }

        /// <summary> 关闭：权限 </summary>
        public SubRole_Close CloseAuth { get; set; }

        /// <summary> 历史：权限 </summary>
        public SubRole_History HistoryAuth { get; set; }
        
        public void Union(ref List<SubRoleItem> ItemList, SubRoleItem Item, md_User U)
        {
            IEnumerable<SubRoleItem> ieQuery = from x in ItemList
                                                where x.Type == L_SubRoleType.Self
                                                where x.ProjectCtegory.ID == Item.ProjectCtegory.ID
                                                where x.Own.Guid == U.Guid
                                                select x;
            if(ieQuery.Any())
            {
                SubRoleItem Tmp = ieQuery.First();
                Tmp.Union(Item);
            }
            else
            {
                Item.Own = U;
                Item.Type = L_SubRoleType.Self;
                ItemList.Add(Item);
            }
        }

        public void Union(ref List<SubRoleItem> ItemList, SubRoleItem Item, md_Department D)
        {
            IEnumerable<SubRoleItem> ieQuery = from x in ItemList
                                                where x.Type == L_SubRoleType.Self
                                                where x.ProjectCtegory.ID == Item.ProjectCtegory.ID
                                                where x.Department.Guid == D.Guid
                                                select x;
            if(ieQuery.Any())
            {
                SubRoleItem Tmp = ieQuery.First();
                Tmp.Union(Item);
            }
            else
            {
                Item.Department = D;
                Item.Type = L_SubRoleType.Department;
                ItemList.Add(Item);
            }
        }

        public void Union(SubRoleItem Item)
        {
            this.OpenAuth.Union(Item.OpenAuth);
            this.UploadAuth.Union(Item.UploadAuth);
            this.AuditAuth.Union(Item.AuditAuth);
            this.AdjustAuth.Union(Item.AdjustAuth);
            this.InUseAuth.Union(Item.InUseAuth);
            this.CompleteAuth.Union(Item.CompleteAuth);
            this.CloseAuth.Union(Item.CloseAuth);
            this.HistoryAuth.Union(Item.HistoryAuth);
        }
        
        public void AddCheck(ref List<CheckRightItem> CheckList, ref List<CheckRightItem> HisCheckList, md_Department D)
        {
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Query, OpenAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Upload, OpenAuth.CanUpload, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Approve, OpenAuth.CanApprove, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.ChangeStatus, OpenAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Query, UploadAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Upload, UploadAuth.CanUpload, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Delete, UploadAuth.CanDelete, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Approve, UploadAuth.CanApprove, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.ChangeStatus, UploadAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Query, AuditAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Approve, AuditAuth.CanApprove, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Modify, AuditAuth.CanModify, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.ChangeStatus, AuditAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Query, InUseAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Adjust, InUseAuth.CanAdjust, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Transfer, InUseAuth.CanTransfer, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Paid, InUseAuth.CanPaid, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Query, AdjustAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Upload, AdjustAuth.CanUpload, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Delete, AdjustAuth.CanDelete, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Approve, AdjustAuth.CanApprove, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.ChangeStatus, AdjustAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Complete, L_ActionType.Query, CompleteAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Complete, L_ActionType.ChangeStatus, CompleteAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddCheckItem(ref CheckList, L_BudgetStatus.Close, L_ActionType.Query, CloseAuth.CanQuery, this.ProjectCtegory, D);
            AddCheckItem(ref CheckList, L_BudgetStatus.Close, L_ActionType.ChangeStatus, CloseAuth.CanChangeStatus, this.ProjectCtegory, D);

            AddHisCheckItem(ref HisCheckList, HistoryAuth.CanQuery, this.ProjectCtegory, D);

        }

        public void AddCheck(ref List<CheckRightItem> CheckList, ref List<CheckRightItem> HisCheckList, md_User U)
        {
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Query, OpenAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Upload, OpenAuth.CanUpload, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.Approve, OpenAuth.CanApprove, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Open, L_ActionType.ChangeStatus, OpenAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Query, UploadAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Upload, UploadAuth.CanUpload, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Delete, UploadAuth.CanDelete, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.Approve, UploadAuth.CanApprove, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Upload, L_ActionType.ChangeStatus, UploadAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Query, AuditAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Approve, AuditAuth.CanApprove, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.Modify, AuditAuth.CanModify, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Approve, L_ActionType.ChangeStatus, AuditAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Query, InUseAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Adjust, InUseAuth.CanAdjust, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Transfer, InUseAuth.CanTransfer, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Use, L_ActionType.Paid, InUseAuth.CanPaid, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Query, AdjustAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Upload, AdjustAuth.CanUpload, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Delete, AdjustAuth.CanDelete, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.Approve, AdjustAuth.CanApprove, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Adjust, L_ActionType.ChangeStatus, AdjustAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Complete, L_ActionType.Query, CompleteAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Complete, L_ActionType.ChangeStatus, CompleteAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddCheckItem(ref CheckList, L_BudgetStatus.Close, L_ActionType.Query, CloseAuth.CanQuery, this.ProjectCtegory, U);
            AddCheckItem(ref CheckList, L_BudgetStatus.Close, L_ActionType.ChangeStatus, CloseAuth.CanChangeStatus, this.ProjectCtegory, U);

            AddHisCheckItem(ref HisCheckList, HistoryAuth.CanQuery, this.ProjectCtegory, U);

        }

        private void AddCheckItem(ref List<CheckRightItem> CL, L_BudgetStatus S, L_ActionType A, Boolean CAN, list_ProjectCategory PC, md_Department D)
        {
            if (CAN && !CL.Any(o => o.ProjectCtegory.ID == PC.ID
                && o.Department.Guid == D.Guid
                && o.Status == S
                && o.Action == A))
            {
                CL.Add(new CheckRightItem()
                {
                    ProjectCtegory = PC,
                    Department = D,
                    Status = S,
                    Action = A,
                    Type = L_CheckType.Department,
                     
                });
            }
        }

        private void AddCheckItem(ref List<CheckRightItem> CL, L_BudgetStatus S, L_ActionType A, Boolean CAN, list_ProjectCategory PC, md_User U)
        {
            if (CAN && !CL.Any(o => o.ProjectCtegory.ID == PC.ID
                && o.PIC.Guid == U.Guid
                && o.Status == S
                && o.Action == A))
            {
                CL.Add(new CheckRightItem()
                {
                    ProjectCtegory = PC,
                    PIC = U,
                    Status = S,
                    Action = A,
                    Type = L_CheckType.User
                });
            }
        }

        private void AddHisCheckItem(ref List<CheckRightItem> CL, Boolean CAN, list_ProjectCategory PC, md_Department D)
        {
            if (CAN && !CL.Any(o => o.ProjectCtegory.ID == PC.ID
                && o.Department.Guid == D.Guid))
            {
                CL.Add(new CheckRightItem()
                {
                    ProjectCtegory = PC,
                    Department = D,
                    Type = L_CheckType.Department,
                    Action = L_ActionType.Query,
                });
            }
        }

        private void AddHisCheckItem(ref List<CheckRightItem> CL, Boolean CAN, list_ProjectCategory PC,  md_User U)
        {
            if (CAN && !CL.Any(o => o.ProjectCtegory.ID == PC.ID
                && o.PIC.Guid == U.Guid))
            {
                CL.Add(new CheckRightItem()
                {
                    ProjectCtegory = PC,
                    PIC = U,
                    Type = L_CheckType.User,
                    Action = L_ActionType.Query,
                });
            }
        }
    }

    public class CheckRightItem
    {
        public CheckRightItem()
        {
            ProjectCtegory = new list_ProjectCategory();
            Department = new md_Department();
            PIC = new md_User();
        }

        public list_ProjectCategory ProjectCtegory { get; set; }

        public md_Department Department { get; set; }

        public md_User PIC { get; set; }
        
        public L_BudgetStatus Status  { get; set; }

        public L_ActionType Action { get; set; }
        
        public L_CheckType Type { get; set; }
    }

    public class RoleItem
    {
        public RoleItem()
        {
            RoleList = new List<SubRoleItem>();
            Role = new md_Role();
            PageList = new List<string>();
        }

        public List<SubRoleItem> RoleList { get; set; }

        public md_Role Role { get; set; }

        public List<String> PageList { get; set; }
    }

    #endregion

    #region Item.RoleRelation
    
    public class RoleRelationItem
    {
        public RoleRelationItem()
        {
            User = new UserItem();
            RoleList = new List<SelectListItem>();
        }

        public UserItem User { get; set; }

        public List<SelectListItem> RoleList { get; set; }
    }
    
    #endregion

    #region Item.Excel
    
    [Serializable]
    public class ExcelSheetCellItem
    {
        public ExcelSheetCellItem()
        {
            Text = String.Empty;
            Error = String.Empty;
            InList = new Dictionary<string, string>();
            IsRequired = false;
            IsList = false;
            IsDate = false;
            IsDecimal = false;
            MaxLength = 0;
            Value = String.Empty;
            IsError = false;
        }

        public String Text { get; set; }

        public String Value { get; set; }

        public String Error { get; set; }
        
        public Dictionary<String, String> InList { get; set; }

        public Boolean IsError { get; set; }

        /// <summary>必填校验</summary>
        public Boolean IsRequired { get; set; }

        /// <summary>必须属于序列</summary>
        public Boolean IsList { get; set; }

        /// <summary>日期校验</summary>
        public Boolean IsDate { get; set; }

        /// <summary>数字校验</summary>
        public Boolean IsNum { get; set; }

        /// <summary>金额校验</summary>
        public Boolean IsDecimal { get; set; }

        /// <summary>长度校验</summary>
        public Int32 MaxLength { get; set; }
    }

    public class ExcelSheetItem
    {
        public ExcelSheetItem()
        {
        }

        public static Boolean Check(List<Dictionary<String, ExcelSheetCellItem>> Table)
        {
            Boolean blResult = true;

            DateTime dtCheck = new DateTime();
            Decimal dCheck = new Decimal();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            List<String> lsProject = new List<string>();
            List<String> lsBudget = new List<string>();

            for (int m = 0; m < Table.Count; m++)
            {
                foreach (String n in Table[m].Keys)
                {
                    #region Cell校验:必输

                    if (Table[m][n].IsRequired)
                    {
                        if (String.IsNullOrEmpty(Table[m][n].Text))
                        {
                            Table[m]["检查结果"].Text += String.Format("“{0}”必须输入<br/>", n);
                            Table[m][n].Error = "必须输入";
                            Table[m][n].IsError = true;
                            blResult = false;
                            continue;
                        }
                    }

                    #endregion

                    #region Cell校验:文字长度

                    if (Table[m][n].MaxLength > 0)
                    {
                        if (Table[m][n].Text.Length > Table[m][n].MaxLength)
                        {
                            Table[m]["检查结果"].Text += String.Format("“{0}”文本长度超过{1}字<br/>", n, Table[m][n].MaxLength);
                            Table[m][n].Error = "文本超长";
                            Table[m][n].IsError = true;
                            blResult = false;
                            continue;
                        }
                    }

                    #endregion

                    #region Cell校验:日期格式

                    if (!String.IsNullOrEmpty(Table[m][n].Text.Trim()) && Table[m][n].IsDate)
                    {
                        if (!DateTime.TryParse(Table[m][n].Text, out dtCheck))
                        {
                            Table[m]["检查结果"].Text += String.Format("“{0}”请填写正确的日期<br/>", n);
                            Table[m][n].Error = "请填写正确的日期";
                            Table[m][n].IsError = true;
                            blResult = false;
                            continue;
                        }
                    }
                    #endregion

                    #region Cell校验:金额格式

                    if (!String.IsNullOrEmpty(Table[m][n].Text.Trim()) && Table[m][n].IsDecimal)
                    {
                        if (!Decimal.TryParse(Table[m][n].Text, out dCheck))
                        {
                            Table[m]["检查结果"].Text += String.Format("“{0}”请填写正确的金额<br/>", n);
                            Table[m][n].Error = "请填写正确的金额";
                            Table[m][n].IsError = true;
                            blResult = false;
                            continue;
                        }
                    }
             
                    #endregion

                    #region Cell校验:有效性

                    if (!String.IsNullOrEmpty(Table[m][n].Text.Trim()) && Table[m][n].InList.Count > 0)
                    {
                        if (!Table[m][n].InList.ContainsKey(Table[m][n].Text))
                        {
                            Table[m]["检查结果"].Text += String.Format("“{0}”请填写正确内容<br/>", n);
                            Table[m][n].Error = "请填写正确内容";
                            Table[m][n].IsError = true;
                            blResult = false;
                            continue;
                        }
                        else
                            Table[m][n].Value = Table[m][n].InList[Table[m][n].Text];
                    }

                    #endregion                    
                }

                #region Row校验:项目负责人与编制单位对应

                if (!(from d in DB.md_Departments
                      from u in DB.md_Users
                      where d.Guid == u.DepartmentGuid
                      where d.DepartmentName == Table[m]["编制单位"].Text
                      where u.UserName == Table[m]["项目负责人"].Text
                      select u).Any())
                {
                    Table[m]["检查结果"].Text += "编制单位和项目负责人的对应关系不正确";
                    Table[m]["编制单位"].IsError = true;
                    Table[m]["项目负责人"].IsError = true;
                    blResult = false;
                }

                #endregion

                #region Row校验:项目创建时，重复项目代码校验

                if (Table[m]["处理方案"].Value.Contains("ADD PROJECT"))
                {
                    if (lsProject.Contains(Table[m]["项目代号"].Text))
                    {
                        Table[m]["检查结果"].Text += "创建项目重复";
                        Table[m]["项目代号"].IsError = true;
                        blResult = false;
                    }
                    else
                        lsProject.Add(Table[m]["项目代号"].Text);
                }

                #endregion

                #region Row校验:预算创建时，重复预算校验

                if (Table[m]["处理方案"].Value.Contains("ADD BUDGET"))
                {
                    if (lsBudget.Contains(Table[m]["项目代号"].Text + "-" + Table[m]["年度"].Text))
                    {
                        Table[m]["检查结果"].Text += "创建预算重复";
                        Table[m]["项目代号"].IsError = true;
                        blResult = false;
                    }
                    else
                        lsBudget.Add(Table[m]["项目代号"].Text + "-" + Table[m]["年度"].Text);
                }

                #endregion

                #region Row校验:类别不能变更

                if (Table[m]["处理方案"].Value.Contains("ADJUST PROJECT"))
                {
                    if (!(from p in DB.md_Projects
                         from pc in DB.list_ProjectCategories
                         where p.ProjectCategoryID == pc.ID
                         where p.ProjectCode == Table[m]["项目代号"].Text
                          where pc.Name == Table[m]["类别"].Text
                         select p).Any())
                    {
                        Table[m]["检查结果"].Text += "类别不能变更";
                        Table[m]["类别"].IsError = true;
                        blResult = false;
                    }
                }

                #endregion

                #region Row校验:类型不能变更

                if (Table[m]["处理方案"].Value.Contains("ADJUST PROJECT") && Table[m]["类型"].IsRequired == true)
                {
                    if (!(from p in DB.md_Projects
                          from pt in DB.list_ProjcetTypes
                          where p.ProjectTypeID == pt.ID
                          where p.ProjectCode == Table[m]["项目代号"].Text
                          where pt.Name == Table[m]["类型"].Text
                          select p).Any())
                    {
                        Table[m]["检查结果"].Text += "类型不能变更";
                        Table[m]["类型"].IsError = true;
                        blResult = false;
                    }
                }

                #endregion

                #region Row校验：总结

                if (Table[m].Where(o => o.Value.IsError).Any())
                {
                    //Table[m]["检查结果"].Text = "不通过";
                    Table[m]["处理方案"].Text += "<br/>不提交，请检查模版";
                }
                else
                {
                    Table[m]["检查结果"].Text = "通过";
                }

                #endregion
            }

            DB.Connection.Close();

            return blResult;
        }

        public static Boolean Check(List<List<ExcelSheetCellItem>> Table)
        {
            Boolean blResult = true;

            DateTime dtCheck = new DateTime();
            Decimal dCheck = new Decimal();

            for (int m = 0; m < Table.Count; m++)
            {
                for (int n = 0; n < Table[m].Count; n++)
                {
                    if (Table[m][n].IsRequired)
                    {
                        if (String.IsNullOrEmpty(Table[m][n].Text))
                        {
                            Table[m][n].Error = "必须输入";
                            blResult = false;
                            continue;
                        }
                    }

                    if (Table[m][n].IsDate) {
                        if (!DateTime.TryParse(Table[m][n].Text, out dtCheck))
                        {
                            Table[m][n].Error = "请填写正确的日期";
                            blResult = false;
                            continue;
                        }
                    }

                    if(Table[m][n].IsDecimal){
                        if (!Decimal.TryParse(Table[m][n].Text, out dCheck))
                        {
                            Table[m][n].Error = "请填写正确的金额";
                            blResult = false;
                            continue;
                        }
                    }

                    if (Table[m][n].IsList)
                    {
                        if (!Table[m][n].InList.ContainsValue(Table[m][n].Text))
                        {
                            Table[m][n].Error = "请填写正确内容";
                            blResult = false;
                            continue;
                        }
                    }                    
                }
            }

            return blResult;
        }

        public static void GetList(
                ref List<String> lsProjectCategory
            ,ref  List<String> lsProjcetType
            ,ref  List<String> lsBudgetStatus
            ,ref  List<String> lsYesOrNo
            ,ref  List<String> lsDepartment
            ,ref List<String> lsAnnualProgress
            ,ref List<String> lsUser
            ,ref List<String> lsYear)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            lsProjectCategory = (from x in DB.list_ProjectCategories select x.Name).ToList();

            lsProjcetType = (from x in DB.list_ProjcetTypes select x.Name).ToList();

            lsBudgetStatus = (from x in DB.list_BudgetStatus select x.Name).ToList();

            lsYesOrNo = (from x in DB.list_YesOrNos select x.Name).ToList();

            lsDepartment = (from x in DB.md_Departments where x.Status select x.DepartmentName).ToList();

            lsAnnualProgress = (from x in DB.list_AnnualProgresses select x.Name).ToList();

            lsUser = (from x in DB.md_Users where x.Status select x.UserName).ToList();

            lsYear = (from x in DB.list_Years select x.Name).ToList();

            DB.Connection.Close();
        }
        
        public static Dictionary<String, String> GetList_YN()
        {
            Dictionary<String, String> lsYesOrNo = new Dictionary<string, string>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            lsYesOrNo = (from x in DB.list_YesOrNos select x).ToDictionary(o => o.Value, o => o.Name);

            DB.Connection.Close();

            return lsYesOrNo;
        }

        public static Dictionary<String, String> GetList_AdvenceStatus()
        {
            Dictionary<String, String> lsAdvenceStatus = new Dictionary<string, string>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            lsAdvenceStatus = (from x in DB.list_AdvenceStatus select x).ToDictionary(o => o.Status, o => o.Name);

            DB.Connection.Close();

            return lsAdvenceStatus;
        }

        public static void GetList(
             ref Dictionary<String, String> lsProjectCategory
            ,ref Dictionary<String, String> lsProjcetType
            ,ref Dictionary<String, String> lsBudgetStatus
            ,ref Dictionary<String, String> lsYesOrNo
            ,ref Dictionary<String,String> lsDepartment
            ,ref Dictionary<String, String> lsAnnualProgress
            ,ref Dictionary<String,String> lsUser
            ,ref Dictionary<String, String> lsYear)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            lsProjectCategory = (from x in DB.list_ProjectCategories select x).ToDictionary(o=>o.Name, o=>o.ID.ToString());

            lsProjcetType = (from x in DB.list_ProjcetTypes select x).ToDictionary(o => o.Name, o => o.ID.ToString());

            lsBudgetStatus = (from x in DB.list_BudgetStatus select x).ToDictionary(o => o.Name, o => o.Status.ToString());

            lsYesOrNo = (from x in DB.list_YesOrNos select x).ToDictionary(o => o.Name, o => o.Value.ToString());

            lsDepartment = (from x in DB.md_Departments where x.Status select x).ToDictionary(o=>o.DepartmentName, o=>o.Guid);

            lsAnnualProgress = (from x in DB.list_AnnualProgresses select x).ToDictionary(o => o.Name, o => o.ID.ToString());

            lsUser = (from x in DB.md_Users where x.Status select x).ToDictionary(o=>o.UserName, o=>o.Guid);

            lsYear = (from x in DB.list_Years select x).ToDictionary(o => o.Name, o => o.ID.ToString());

            DB.Connection.Close();
        }
    }

    public class ExcelUilityItem
    {
        public ExcelUilityItem() { }

        public void AddList(ref Excel.Worksheet ws, String Cell, IEnumerable<String> ieList, String ErrorMsg)
        {
            String List = String.Empty;
            List<String> lsList = new List<string>();
            if (ieList.Any()) { lsList = ieList.ToList(); }
            foreach (String aL in lsList) { List = List + aL + ","; }
            if (List.Length > 0) { List = List.Substring(0, List.Length - 1); }

            ws.get_Range(Cell).Validation.Delete();
            ws.get_Range(Cell).Validation.Add(Excel.XlDVType.xlValidateList
                , Excel.XlDVAlertStyle.xlValidAlertStop
                , Excel.XlFormatConditionOperator.xlBetween
                , List);
            ws.get_Range(Cell).Validation.IgnoreBlank = true;
            ws.get_Range(Cell).Validation.InCellDropdown = true;
            ws.get_Range(Cell).Validation.InputTitle = "";
            ws.get_Range(Cell).Validation.ErrorTitle = "";
            ws.get_Range(Cell).Validation.InputMessage = "";
            ws.get_Range(Cell).Validation.ErrorMessage = ErrorMsg;
            ws.get_Range(Cell).Validation.IMEMode = (int)Excel.XlIMEMode.xlIMEModeNoControl;
            ws.get_Range(Cell).Validation.ShowInput = true;
            ws.get_Range(Cell).Validation.ShowError = true;
        }
    }

    public class TemplateSheetItem
    {
        public TemplateSheetItem()
        {
            BugetInfo = new Dictionary<string, ExcelSheetCellItem>();
            ItemInfo = new List<Dictionary<string, ExcelSheetCellItem>>();
            IsOK = true;
        }

        public Dictionary<String, ExcelSheetCellItem> BugetInfo { get; set; }

        public List<Dictionary<String, ExcelSheetCellItem>> ItemInfo { get; set; }

        public Boolean IsOK { get; set; }

        public static Boolean Check(List<TemplateSheetItem> Table, UserItem U)
        {
            Boolean blReturnResult = true;

            DateTime dtCheck = new DateTime();
            Int32 intCheck = new Int32();
            Decimal dCheck = new Decimal();

            for (int m = 0; m < Table.Count; m++)
            {
                //U.AppCan(L_ActionType.Upload, 人"Table[m].BugetInfo["类别"].Text, Table[m].BugetInfo["编制单位"].Text,Table[m].BugetInfo["项目负责Table[m].BugetInfo["类别"].Text, Table[m].BugetInfo["编制单位"].Text,Table[m].BugetInfo["项目负责].Text,

                //if (U.IsOnlyNormal && new String[] { "1", "2", "3" }.Contains(Table[m].BugetInfo["类别"].Value) && Table[m].BugetInfo["项目负责人"].Text != U.User.UserName)
                //{
                //    Table[m].BugetInfo["检查结果"].Text += "无权提交<br/>";
                //    Table[m].IsOK = false;
                //    continue;
                //}
                //else if (U.IsOnlyNormal && new String[] { "4" }.Contains(Table[m].BugetInfo["类别"].Value) && Table[m].BugetInfo["编制单位"].Text != U.Department.Department.DepartmentName)
                //{
                //    Table[m].BugetInfo["检查结果"].Text += "无权提交<br/>";
                //    Table[m].IsOK = false;
                //    continue;
                //}
                //else if (!U.HasRole(Role.MGR))
                //{
                //    Table[m].BugetInfo["检查结果"].Text += "无权提交<br/>";
                //    Table[m].IsOK = false;
                //    continue;
                //}

                foreach (String n in Table[m].BugetInfo.Keys)
                {
                    if (Table[m].BugetInfo[n].IsRequired)
                    {
                        if (String.IsNullOrEmpty(Table[m].BugetInfo[n].Text))
                        {
                            Table[m].BugetInfo["检查结果"].Text += String.Format("“{0}”必须输入<br/>", n);
                            Table[m].BugetInfo[n].Error = "必须输入";
                            Table[m].BugetInfo[n].IsError = true;
                            Table[m].IsOK = false;
                            continue;
                        }
                    }

                    if (!String.IsNullOrEmpty(Table[m].BugetInfo[n].Text.Trim()) && Table[m].BugetInfo[n].IsDate)
                    {
                        if (!DateTime.TryParse(Table[m].BugetInfo[n].Text, out dtCheck))
                        {
                            Table[m].BugetInfo["检查结果"].Text += String.Format("“{0}”请填写正确的日期<br/>", n);
                            Table[m].BugetInfo[n].Error = "请填写正确的日期";
                            Table[m].BugetInfo[n].IsError = true;
                            Table[m].IsOK = false;
                            continue;
                        }
                    }

                    if (Table[m].BugetInfo[n].IsDecimal)
                    {
                        if (String.IsNullOrEmpty(Table[m].BugetInfo[n].Text.Trim()))
                            Table[m].BugetInfo[n].Text = "0";
                        else
                        {
                            if (!Decimal.TryParse(Table[m].BugetInfo[n].Text, out dCheck))
                            {
                                Table[m].BugetInfo["检查结果"].Text += String.Format("“{0}”请填写正确的金额<br/>", n);
                                Table[m].BugetInfo[n].Error = "请填写正确的金额";
                                Table[m].BugetInfo[n].IsError = true;
                                Table[m].IsOK = false;
                                continue;
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(Table[m].BugetInfo[n].Text.Trim()) && Table[m].BugetInfo[n].InList.Count > 0)
                    {
                        if (!Table[m].BugetInfo[n].InList.ContainsKey(Table[m].BugetInfo[n].Text))
                        {
                            Table[m].BugetInfo["检查结果"].Text += String.Format("“{0}”请填写有效数据<br/>", n);
                            Table[m].BugetInfo[n].Error = "请填写有效数据";
                            Table[m].BugetInfo[n].IsError = true;
                            Table[m].IsOK = false;
                            continue;
                        }
                        else
                            Table[m].BugetInfo[n].Value = Table[m].BugetInfo[n].InList[Table[m].BugetInfo[n].Text];
                    }
                }

                for (int n = 0; n < Table[m].ItemInfo.Count; n++)
                {
                    #region 一般预算提交 Item

                    if (new String[] { "1", "2", "3" }.Contains(Table[m].BugetInfo["类别"].Value))
                    {
                        Int32 intLv = 0;

                        Int32.TryParse(Table[m].ItemInfo[n]["Lv"].Text, out intLv);

                        if (intLv == 3)
                        {
                            if (String.IsNullOrEmpty(Table[m].ItemInfo[n]["支出品名"].Text.Trim())
                                && String.IsNullOrEmpty(Table[m].ItemInfo[n]["数量"].Text.Trim())
                                && String.IsNullOrEmpty(Table[m].ItemInfo[n]["单价"].Text.Trim()))
                            {
                                Table[m].ItemInfo.RemoveAt(n);
                                n--;
                                continue;
                            }
                        }

                        if (intLv == 2 || intLv == 1)
                        {
                            if (String.IsNullOrEmpty(Table[m].ItemInfo[n]["金额"].Text.Trim()))
                                Table[m].ItemInfo[n]["金额"].Text = "0";
                        }

                    }

                    #endregion

                    #region 机关费预算提交 Item

                    if (Table[m].BugetInfo["类别"].Value == "4")
                    {
                        if (String.IsNullOrEmpty(Table[m].ItemInfo[n]["预算开支项目"].Text.Trim())
                            && String.IsNullOrEmpty(Table[m].ItemInfo[n]["数量"].Text.Trim())
                            && String.IsNullOrEmpty(Table[m].ItemInfo[n]["单价"].Text.Trim()))
                        {
                            Table[m].ItemInfo.RemoveAt(n);
                            n--;
                            continue;
                        }
                    }

                    #endregion

                    foreach (String l in Table[m].ItemInfo[n].Keys)
                    {
                        if (Table[m].ItemInfo[n][l].IsRequired)
                        {
                            if (String.IsNullOrEmpty(Table[m].ItemInfo[n][l].Text))
                            {
                                Table[m].BugetInfo["检查结果"].Text += String.Format("明细行{0}:“{1}”必须输入<br/>", Table[m].ItemInfo[n]["Row"].Text, l);
                                Table[m].ItemInfo[n][l].Error = "必须输入";
                                Table[m].ItemInfo[n][l].IsError = true;
                                Table[m].IsOK = false;
                                continue;
                            }
                        }

                        if (Table[m].ItemInfo[n][l].IsDecimal)
                        {

                            if (String.IsNullOrEmpty(Table[m].ItemInfo[n][l].Text.Trim()))
                                Table[m].ItemInfo[n][l].Text = "0";
                            else
                            {
                                if (!Decimal.TryParse(Table[m].ItemInfo[n][l].Text, out dCheck))
                                {
                                    Table[m].BugetInfo["检查结果"].Text += String.Format("明细行{0}:“{1}”请填写正确的金额<br/>", Table[m].ItemInfo[n]["Row"].Text, l);
                                    Table[m].ItemInfo[n][l].Error = "请填写正确的金额";
                                    Table[m].ItemInfo[n][l].IsError = true;
                                    Table[m].IsOK = false;
                                    continue;
                                }
                            }
                        }

                        if (Table[m].ItemInfo[n][l].IsNum)
                        {
                            if (String.IsNullOrEmpty(Table[m].ItemInfo[n][l].Text.Trim()))
                                Table[m].ItemInfo[n][l].Text = "0";
                            else
                            {
                                if (!Int32.TryParse(Table[m].ItemInfo[n][l].Text, out intCheck))
                                {
                                    Table[m].BugetInfo["检查结果"].Text += String.Format("明细行{0}:“{1}”请填写正确的金额<br/>", Table[m].ItemInfo[n]["Row"].Text, l);
                                    Table[m].ItemInfo[n][l].Error = "请填写正确的金额";
                                    Table[m].ItemInfo[n][l].IsError = true;
                                    Table[m].IsOK = false;
                                    continue;
                                }
                            }
                        }
                    }
                }

                if (NormalBudgetUploadModel.GetText_Decimal(Table[m].BugetInfo, "当年支出[上缴利润]") < 0)
                {
                    Table[m].BugetInfo["检查结果"].Text += "上缴利润为负<br/>";
                    Table[m].IsOK = false;
                }


                if (Table[m].IsOK)
                    Table[m].BugetInfo["检查结果"].Text = "通过";
                
                blReturnResult = blReturnResult && Table[m].IsOK;
            }

            return blReturnResult;
        }

        public static void CheckLogic(List<TemplateSheetItem> Table)
        {
            foreach (TemplateSheetItem Row in Table)
            {
                //BudgetItem One = XChange(Row);

                //Decimal TBA = (from c in One.ItemList
                //               from p in One.ItemList
                //               where c.ParentGuid == p.Guid
                //               where p.ItemName == "业务费"
                //               select c.ItemAmount).Sum();

                //Decimal TA = (from c in One.ItemList
                //              where c.ItemLevel == 3
                //              select c.ItemAmount).Sum();

                //Row.BugetInfo.Add("报警信息", new ExcelSheetCellItem());

                //if (Convert.ToBoolean(One.Budget.IsAdvence) && TBA * 5 > One.Budget.BudgetAmount)
                //{
                //    Row.BugetInfo["报警信息"].Text = "业务费超过20%";
                //}

                //if (!Convert.ToBoolean(One.Budget.IsAdvence) && TBA * 5 > One.Budget.BudgetAmount * 2)
                //{
                //    Row.BugetInfo["报警信息"].Text = "业务费超过40%";
                //}

                //if (TA > 0 && TA > One.Budget.BudgetAmount)
                //{
                //    Row.BugetInfo["检查结果"].Text += "支付合计超过预算金额<br/>";
                //    Row.IsOK = false;
                //}

                //if (Convert.ToBoolean(One.Budget.IsAdvence) && (One.Budget.AdvenceBalance + One.Budget.AdvenceAmount) == 0)
                //{
                //    Row.BugetInfo["检查结果"].Text += "垫支信息不正确<br/>";
                //    Row.IsOK = false;
                //}

                //if (!Convert.ToBoolean(One.Budget.IsAdvence) && One.Budget.BudgetAmount <= 0)
                //{
                //    Row.BugetInfo["检查结果"].Text += "预算金额<br/>";
                //    Row.IsOK = false;
                //}
            }
        }

        public static void CheckDB(List<TemplateSheetItem> Table, UserItem U, L_ActionType Action)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();
            
            for (int m = 0; m < Table.Count; m++)
            {
                if (Table[m].IsOK)
                {
                    if (Table[m].IsOK)
                    {
                        IEnumerable<wf_Budget> ieBudget = (from b in DB.wf_Budgets
                                                           from p in DB.md_Projects
                                                           where b.ProjectGuid == p.Guid
                                                           where p.ProjectCode == Table[m].BugetInfo["项目代号"].Text
                                                           where b.Year == Table[m].BugetInfo["年度"].Text
                                                           select b);

                        if (!ieBudget.Any()) //没有预算信息
                        {
                            if (Action == L_ActionType.Upload)
                            {
                                if (!U.AppCan(Action,
                                    new list_ProjectCategory() { ID = Table[m].BugetInfo["类别"].Value },
                                    new md_Department() { DepartmentName = Table[m].BugetInfo["编制单位"].Text },
                                    new md_User() { UserName = Table[m].BugetInfo["项目负责人"].Text },
                                    new list_BudgetStatus() { Status = ((int)L_BudgetStatus.Open).ToString() }))
                                {
                                    Table[m].BugetInfo["检查结果"].Text = "无权提交<br/>";
                                    Table[m].IsOK = false;
                                }
                                Table[m].BugetInfo["处理方案"].Text = "提交预算";
                                Table[m].BugetInfo["处理方案"].Value = "ADD BUDGET";
                            }
                            else
                            {
                                Table[m].BugetInfo["检查结果"].Text = "无预算记录<br/>";
                                Table[m].IsOK = false;
                                Table[m].BugetInfo["处理方案"].Text = "无预算记录，无法处理";
                                Table[m].BugetInfo["处理方案"].Value = "NOTHING";
                            }
                        }
                        else
                        {
                            wf_Budget oBudget = ieBudget.First();

                            if (Action == L_ActionType.Upload)
                            {
                                if (!U.AppCan(Action,
                                    new list_ProjectCategory() { ID = Table[m].BugetInfo["类别"].Value },
                                    new md_Department() { DepartmentName = Table[m].BugetInfo["编制单位"].Text },
                                    new md_User() { UserName = Table[m].BugetInfo["项目负责人"].Text },
                                    new list_BudgetStatus() { Status = oBudget.BudgetStatus }))
                                {
                                    Table[m].BugetInfo["检查结果"].Text = "无权提交<br/>";
                                    Table[m].IsOK = false;
                                }

                                if (oBudget.BudgetStatus == "0" || oBudget.BudgetStatus == "10") //开放提交
                                {
                                    Table[m].BugetInfo["处理方案"].Text = "更新预算";
                                    Table[m].BugetInfo["处理方案"].Value = "UPDATE BUDGET";
                                }
                                else
                                {
                                    Table[m].BugetInfo["处理方案"].Text = "预算目前状态无法提交";
                                    Table[m].BugetInfo["处理方案"].Value = "NOTHING";
                                }
                            }
                            else if (Action == L_ActionType.Approve)
                            {
                                if (!U.AppCan(Action,
                                    new list_ProjectCategory() { ID = Table[m].BugetInfo["类别"].Value },
                                    new md_Department() { DepartmentName = Table[m].BugetInfo["编制单位"].Text },
                                    new md_User() { UserName = Table[m].BugetInfo["项目负责人"].Text },
                                    new list_BudgetStatus() { Status = oBudget.BudgetStatus }))
                                {
                                    Table[m].BugetInfo["检查结果"].Text = "无权更新<br/>";
                                    Table[m].IsOK = false;
                                }

                                Table[m].BugetInfo["处理方案"].Text = "更新预算";
                                Table[m].BugetInfo["处理方案"].Value = "UPDATE BUDGET + UPDATE PROJECT";
                            }
                        }
                    }
                }

                DB.Connection.Close();
            }
        }

        public static void SetExcelCellValue(Excel.Worksheet ws, String Range, String Value, Boolean CanEdit)
        {

            if (!String.IsNullOrEmpty(Value.Trim()))
                ws.get_Range(Range).Value2 = Value;

            if (CanEdit)
            {
                ws.get_Range(Range).Locked = false;
                ws.get_Range(Range).Interior.ColorIndex = 0;
            }
            else
            {
                ws.get_Range(Range).Locked = true;
                ws.get_Range(Range).Interior.ColorIndex = 15;
            }

        }

        public static BudgetItem XChange(TemplateSheetItem Row)
        {
            #region Budget

            BudgetItem Temp = new BudgetItem()
            {
                Project = new ProjectItem()
                {
                    Project = new md_Project()
                    {
                        //Guid = ProjectGuid,
                        ProjectCategoryID = Row.BugetInfo["类别"].Value,
                        ProjectTypeID = Row.BugetInfo["类型"].Value,
                        DepartmentGuid = Row.BugetInfo["编制单位"].Value,
                        ProjectName = Row.BugetInfo["项目名称"].Text,
                        ProjectCode = Row.BugetInfo["项目代号"].Text,
                        FundsSources = XT(Row.BugetInfo, "经费来源"),
                        ProjectBeginTime = XT(Row.BugetInfo, "项目周期-起"),
                        ProjectEndTime = XT(Row.BugetInfo, "项目周期-止"),
                        ProjectPIC = Row.BugetInfo["项目负责人"].Value,
                        //CreateTime = DateTime.Now,
                        //ModifyTime = DateTime.Now
                    }
                },
                Budget = new wf_Budget()
                {
                    //Guid = BudgetGuid,
                    //ProjectGuid = ProjectGuid,
                    Year = Row.BugetInfo["年度"].Text,
                    AnnualProgress = XT(Row.BugetInfo, "年度进度"),
                    IsSoft = XV(Row.BugetInfo, "是否为软课题"),
                    //BudgetStatus = "0",

                    IsAdvence = Row.BugetInfo["是否垫支"].Value,
                    AdvencePlanAmount = Convert.ToDecimal(Row.BugetInfo["拟到经费总额"].Text),
                    AdvencePlanTime = Row.BugetInfo["预计经费到位时间"].Text,
                    AdvenceAmount = Convert.ToDecimal(Row.BugetInfo["垫支金额"].Text),
                    AdvenceReturnTime = Row.BugetInfo["预计归垫时间"].Text,
                    AdvencePIC = Row.BugetInfo["归垫责任人"].Value,
                    AdvenceStatus = (Row.BugetInfo["是否垫支"].Value.ToUpper() == "TRUE" ? "0" : ""),
                    AdvencetRemark = Row.BugetInfo["垫支备注"].Text,
                    AdvenceBalance = XTDecimal(Row.BugetInfo, "垫支转入"),
                    AdvenceNoReturn = XTDecimal(Row.BugetInfo, "尚未归垫"),
                    AdvenceLeft = XTDecimal(Row.BugetInfo, "归垫后余额"),
                    
                    BudgetAmount = Convert.ToDecimal(Row.BugetInfo["预算金额"].Text),
                    Income_StandardFunds = Convert.ToDecimal(Row.BugetInfo["标准领报"].Text),
                    Income_ProjectFunds = Convert.ToDecimal(Row.BugetInfo["项目经费"].Text),
                    Income_Subvention = XTDecimal(Row.BugetInfo, "家底弥补"),
                    Income_DepartmentSubvention = XTDecimal(Row.BugetInfo, "家底弥补[所家底]"),
                    Income_PoliticalSubvention = XTDecimal(Row.BugetInfo, "家底弥补[政治部家底]"),
                    Income_ScienceSubvention = XTDecimal(Row.BugetInfo, "家底弥补[科技处家底]"),
                    Income_MangerSubvention = XTDecimal(Row.BugetInfo, "家底弥补[管理处家底]"),
                    Income_Other = Convert.ToDecimal(Row.BugetInfo["其他收入"].Text),
                    Income_Balance = Convert.ToDecimal(Row.BugetInfo["上年转入"].Text),
                    BudgetRemark = Row.BugetInfo["预算备注"].Text,

                    His_Amount = XTDecimal(Row.BugetInfo, "历年支出"),
                    His_Amount_Equipment = XTDecimal(Row.BugetInfo, "历年支出[设备费]"),
                    His_Amount_Material = XTDecimal(Row.BugetInfo, "历年支出[材料费]"),
                    His_Amount_Coordination = XTDecimal(Row.BugetInfo, "历年支出[协作费]"),
                    His_Amount_Bussiness = XTDecimal(Row.BugetInfo, "历年支出[业务费]"),
                    His_Amount_Charge = XTDecimal(Row.BugetInfo, "历年支出[分摊费用]"),
                    His_Amount_Prime = XTDecimal(Row.BugetInfo, "历年支出[成本性]"),
                    His_Amount_Public = XTDecimal(Row.BugetInfo, "历年支出[公用费用]"),
                    His_Remark = XT(Row.BugetInfo, "历年支出备注"),

                    ActualPay_Amount = XTDecimal(Row.BugetInfo, "当年支出实际"),
                    ActualPay_Amount_Equipment = XTDecimal(Row.BugetInfo, "当年支出实际[设备费]"),
                    ActualPay_Amount_Material = XTDecimal(Row.BugetInfo, "当年支出实际[材料费]"),
                    ActualPay_Amount_Coordination = XTDecimal(Row.BugetInfo, "当年支出实际[协作费]"),
                    ActualPay_Amount_Bussiness = XTDecimal(Row.BugetInfo, "当年支出实际[业务费]"),
                    ActualPay_Amount_Charge = XTDecimal(Row.BugetInfo, "当年支出实际[分摊费用]"),
                    ActualPay_Amount_Prime = XTDecimal(Row.BugetInfo, "当年支出实际[成本性]"),
                    ActualPay_Amount_Public = XTDecimal(Row.BugetInfo, "当年支出实际[公用费用]"),
                    ActualPay_Remark = XT(Row.BugetInfo, "当年支出实际备注"),

                    //BudgetPay_Amount = GetText_Decimal(Row.BugetInfo, "当年支出"),
                    BudgetPay_Amount_Equipment = XTDecimal(Row.BugetInfo, "当年支出[设备费]"),
                    BudgetPay_Amount_Material = XTDecimal(Row.BugetInfo, "当年支出[材料费]"),
                    BudgetPay_Amount_Coordination = XTDecimal(Row.BugetInfo, "当年支出[协作费]"),
                    BudgetPay_Amount_Bussiness = XTDecimal(Row.BugetInfo, "当年支出[业务费]"),
                    BudgetPay_Amount_Charge = XTDecimal(Row.BugetInfo, "当年支出[分摊费用]"),
                    BudgetPay_Amount_Budget = XTDecimal(Row.BugetInfo, "当年支出[待预算经费]"),
                    BudgetPay_Amount_Profit = XTDecimal(Row.BugetInfo, "当年支出[上缴利润]"),
                    BudgetPay_Amount_Prime = XTDecimal(Row.BugetInfo, "当年支出[成本性]"),
                    BudgetPay_Amount_Public = XTDecimal(Row.BugetInfo, "当年支出[公用费用]"),
                    BudgetPay_Remark = XT(Row.BugetInfo, "当年支出备注")
                }
            };

            #endregion

            String strLv1Guid = String.Empty;
            String strLv2Guid = String.Empty;
            String strPGuid = String.Empty;
            Int32 intNum = 0;

            #region 一般预提提交

            if (new String[] { "1", "2", "3" }.Contains(Temp.Project.Project.ProjectCategoryID))
            {
                foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                {
                    String ItemGuid = Guid.NewGuid().ToString();

                    if (oItem["Lv"].Text == "1") { strLv1Guid = ItemGuid; }

                    if (oItem["Lv"].Text == "2") { strLv2Guid = ItemGuid; }

                    switch (oItem["Lv"].Text)
                    {
                        case "1":
                            strPGuid = null;
                            break;
                        case "2":
                            strPGuid = strLv1Guid;
                            break;
                        case "3":
                            strPGuid = strLv2Guid;
                            break;
                    }

                    intNum++;

                    wf_BudgetItem TempItem = new wf_BudgetItem()
                    {
                        Guid = ItemGuid,
                        //BudgetGuid = BudgetGuid,
                        Number = intNum,
                        ParentGuid = strPGuid,
                        ItemSN = oItem["序号"].Text,
                        ItemName = oItem["支出品名"].Text,
                        ItemRem = oItem["备注"].Text,
                        ItemLevel = Convert.ToInt32(oItem["Lv"].Text)
                    };

                    if (!String.IsNullOrEmpty(oItem["数量"].Text))
                        TempItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                    if (!String.IsNullOrEmpty(oItem["单价"].Text))
                        TempItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                    if (!String.IsNullOrEmpty(oItem["金额"].Text))
                        TempItem.ItemAmount = Convert.ToDecimal(oItem["金额"].Text);

                    Temp.ItemList.Add(TempItem);
                }
            }

            #endregion

            #region 机关费预提提交

            if (Temp.Project.Project.ProjectCategoryID == "4")
            {
                intNum = 2;

                Decimal TotalAmount = 0;

                strLv1Guid = Guid.NewGuid().ToString();
                strLv2Guid = Guid.NewGuid().ToString();

                foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                {
                    String ItemGuid = Guid.NewGuid().ToString();

                    intNum++;

                    wf_BudgetItem TempItem = new wf_BudgetItem()
                    {
                        //Guid = ItemGuid,
                        //BudgetGuid = BudgetGuid,
                        Number = intNum,
                        ParentGuid = strLv2Guid,
                        ItemSN = oItem["序号"].Text,
                        ItemName = oItem["预算开支项目"].Text,
                        ItemRem = oItem["备注"].Text,
                        ItemLevel = 3,
                        ItemUnit = oItem["单位"].Text,
                    };

                    if (!String.IsNullOrEmpty(oItem["数量"].Text))
                        TempItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                    if (!String.IsNullOrEmpty(oItem["单价"].Text))
                        TempItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                    if (!String.IsNullOrEmpty(oItem["预算开支金额"].Text))
                    {
                        TempItem.ItemAmount = Convert.ToDecimal(oItem["预算开支金额"].Text);

                        TotalAmount = TotalAmount + TempItem.ItemAmount;
                    }

                    Temp.ItemList.Add(TempItem);
                }
            }

            #endregion

            return Temp;
        }

        private static Decimal XTDecimal(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
            {
                Decimal decTemp = 0;
                Decimal.TryParse(array[Key].Text, out decTemp);
                return decTemp;
            }
            else
                return 0;
        }

        private static String XT(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
                return array[Key].Text;
            else
                return String.Empty;
        }

        private static String XV(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
                return array[Key].Value;
            else
                return String.Empty;
        }

        public override string ToString()
        {
            String T = "\t";
            String R = "\r\n";

            string X = String.Empty;

            X = X + "Info" + R;

            String H = String.Empty;
            String C = String.Empty;

            foreach (String K in this.BugetInfo.Keys)
            {
                H = H + K + T;

                C = C + this.BugetInfo[K].Text + T;
            }

            X = X + H + R;
            X = X + C + R;
            X = X + R;

            X = X + "ItemList" + R;
            
            for (int i = 0; i < this.ItemInfo.Count; i++)
            {
                String I_H = String.Empty;
                String I_C = String.Empty;

                foreach (String K in this.ItemInfo[i].Keys)
                {
                    if (i == 0)
                        I_H = I_H + K + T;
                    I_C = I_C + this.ItemInfo[i][K].Text + T;
                }

                if (i == 0)
                    X = X + I_H + R;
                X = X + I_C + R;
            }

            return X;
        }
    }

    #endregion
    
    #region Item.Project

    public class ProjectItem
    {
        public ProjectItem()
        {
            ProjectCategory = new list_ProjectCategory();
            ProjcetType = new list_ProjcetType();
            Department = new md_Department();
            Project = new md_Project();
            ProjcetPIC = new md_User();
        }

        public list_ProjectCategory ProjectCategory { get; set; }

        public list_ProjcetType ProjcetType { get; set; }

        public md_Department Department { get; set; }

        public md_Project Project { get; set; }

        public md_User ProjcetPIC { get; set; }

        public IEnumerable<wf_Budget> Budget { get; set; }
    }

    #endregion
}

namespace WebSite.Models
{
    #region Models.Department

    public class DepartmentModel:BaseModel
    {
        public DepartmentModel()
        {
            //Table = new List<DepartmentItem>();
            //Insert = new DepartmentItem();
            DeptList = new List<md_Department>();
            IsAll = false;
        }

        public Boolean IsAll { get; set; }

        public List<md_Department> DeptList { get; set; }

        //public List<DepartmentItem> Table { get; set; }

        //public DepartmentItem Insert { get; set; }

        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                IEnumerable<md_Department> ieTmp = from x in DB.md_Departments
                                                   where this.IsAll || x.Status
                                                   orderby x.OrderID
                                                   select x;

                if (ieTmp.Any())
                    this.DeptList = ieTmp.ToList();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }
        }

        public String InsertItem(md_Department Insert)
        {
            if (Insert.DepartmentName.Trim() == String.Empty)
                return "组织名称不能为空";

            String R = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                if((from x in DB.md_Departments where x.DepartmentName == Insert.DepartmentName.Trim() select x).Any())
                {
                    return "该组织已存在";
                }

                IEnumerable<Int32> ieOrderID =
                    from x in DB.md_Departments
                    select x.OrderID;

                Int32 intMaxOrderID = 0;

                if (ieOrderID.Any())
                    intMaxOrderID = ieOrderID.Max() + 1;
                
                DB.md_Departments.InsertOnSubmit(
                    new md_Department()
                    {
                        //DepartmentLevel = Insert.DepartmentLevel,
                        DepartmentName = Insert.DepartmentName,
                        Guid = Insert.Guid,
                        //ParentGuid = Insert.ParentGuid,
                        Status = true,
                        OrderID = intMaxOrderID
                    });

                String LogDes = String.Format("[新数据][组织名：{0}]"
                    , Insert.DepartmentName);

                String KeyDes = String.Format("[New][ DepartmentName = '{0}' ]"
                    , Insert.DepartmentName);

                CommonItem.WirteLog(DB, L_LogType.MD_User_Insert, LogDes, Insert.Guid, KeyDes, U);

                DB.SubmitChanges();

                R = "组织新建成功";
            }
            catch (Exception Ex)
            {
                R = "组织新建失败";

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Insert, Ex, String.Format("[DepartmentModel.InsertItem][参数：{0}]", Insert.DepartmentName), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return R;
        }

        public String UpdateItem(md_Department Update)
        {
            String R = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_Department> ieSelf =
                    from x in DB.md_Departments
                    where x.Guid == Update.Guid
                    select x;

                String LogDes = String.Format("[原数据][组织名：{0}] => [新数据][组织名：{1}]"
                    , ieSelf.First().DepartmentName
                    , Update.DepartmentName);

                String KeyDes = String.Format("[Old][ DepartmentName = '{0}' ] => [New][ DepartmentName = '{1}' ]"
                    , ieSelf.First().DepartmentName
                    , Update.DepartmentName);

                ieSelf.First().DepartmentName = Update.DepartmentName;

                CommonItem.WirteLog(DB, L_LogType.MD_Department_Update, LogDes, Update.Guid, KeyDes, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                R = "组织修改成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                R = "组织修改失败";

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Update, Ex, String.Format("[DepartmentModel.UpdateItem][参数：{0},{1}]", Update.Guid, Update.DepartmentName), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return R;
        }

        public String DisableItem(md_Department Disable)
        {
            String R = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_Department> ieSelf =
                    from x in DB.md_Departments
                    where x.Guid == Disable.Guid
                    select x;

                String LogDes = String.Format("[原数据][组织名：{0}, 有效] => [新数据][组织名：{0}, 无效]", ieSelf.First().DepartmentName);

                ieSelf.First().Status = false;

                CommonItem.WirteLog(DB, L_LogType.MD_Department_Disable, LogDes, ieSelf.First().Guid, String.Empty, U);
                
                DB.SubmitChanges();

                DB.Transaction.Commit();

                R = "组织已无效";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                R = "组织无效失败";

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Disable, Ex, String.Format("[DepartmentModel.DisableItem][参数：{0}]", Disable.Guid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return R;
        }

        public String EnableItem(md_Department Enable)
        {
            String R = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_Department> ieSelf =
                    from x in DB.md_Departments
                    where x.Guid == Enable.Guid
                    select x;

                String LogDes = String.Format("[原数据][组织名：{0}, 无效] => [新数据][组织名：{0}, 有效]", ieSelf.First().DepartmentName);

                ieSelf.First().Status = true;

                CommonItem.WirteLog(DB, L_LogType.MD_Department_Enable, LogDes, ieSelf.First().Guid, String.Empty, U);
                
                DB.SubmitChanges();

                DB.Transaction.Commit();

                R = "组织已有效";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                R = "组织有效失败";

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Enable, Ex, String.Format("[DepartmentModel.EnableItem][参数：{0}]", Enable.Guid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return R;
        }

        public DBOperationResult UpItem(md_Department Up, Boolean IsAll)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_Department> ieSelf =
                    from x in DB.md_Departments
                    where x.Guid == Up.Guid
                    select x;

                if (!ieSelf.Any())
                    return DBOperationResult.Update_Fail_NoRecord;

                md_Department oTmp = ieSelf.First();

                IEnumerable<md_Department> ieUp = from x in DB.md_Departments
                                                  where IsAll || x.Status
                                                  where x.OrderID < oTmp.OrderID
                                                  orderby x.OrderID descending
                                                  select x;

                String LogDes = String.Format("[上移][组织名：{0}]", ieSelf.First().DepartmentName);

                if (ieUp.Any())
                {
                    Int32 TmpOrderID = ieUp.First().OrderID;

                    ieUp.First().OrderID = oTmp.OrderID;
                    oTmp.OrderID = TmpOrderID;
                }

                CommonItem.WirteLog(DB, L_LogType.MD_Department_Up, LogDes, Up.Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Up, Ex, String.Format("[DepartmentModel.UpItem][参数：{0}]", Up.Guid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return DBOperationResult.Update_Success;
        }

        public DBOperationResult DwItem(md_Department Dw, Boolean IsAll)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_Department> ieSelf =
                    from x in DB.md_Departments
                    where x.Guid == Dw.Guid
                    select x;

                if (!ieSelf.Any())
                    return DBOperationResult.Update_Fail_NoRecord;

                md_Department oTmp = ieSelf.First();

                IEnumerable<md_Department> ieDw = from x in DB.md_Departments
                                                  where IsAll || x.Status
                                                  where x.OrderID > oTmp.OrderID
                                                  orderby x.OrderID
                                                  select x;

                String LogDes = String.Format("[下移][组织名：{0}]", ieSelf.First().DepartmentName);

                if (ieDw.Any())
                {
                    Int32 TmpOrderID = ieDw.First().OrderID;
                    ieDw.First().OrderID = oTmp.OrderID;
                    oTmp.OrderID = TmpOrderID;
                }

                CommonItem.WirteLog(DB, L_LogType.MD_Department_Down, LogDes, Dw.Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_Department_Down, Ex, String.Format("[DepartmentModel.DwItem][参数：{0}]", Dw.Guid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return DBOperationResult.Update_Success;
        }
        
    }

    #endregion

    #region Models.User

    [Serializable]
    public class UserModel:BaseModel
    {
        public UserModel()
        {
            Table = new List<WebUserItem>();
            Insert = new WebUserItem();
            Query_ShowAll = false;
        }

        public String Query_UserName { get; set; }

        public String Query_DepartmentName { get; set; }

        public String Query_RoleName { get; set; }

        public Boolean Query_ShowAll { get; set; }

        public List<WebUserItem> Table { get; set; }

        public WebUserItem Insert { get; set; }

        public IEnumerable<SelectListItem> RoleSource { get; set; }

        public void Init()
        {
            this.Table = GetTable();
            this.Insert = GetInsert();
            this.RoleSource = GetRoleSource();
        }

        private List<WebUserItem> GetTable()
        {
            List<WebUserItem> List = new List<WebUserItem>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = (from u in DB.md_Users
                        from d in DB.md_Departments
                        where u.DepartmentGuid == d.Guid
                        //where u.Status
                        orderby u.OrderID
                        select new WebUserItem
                        {
                            User = u,
                            Department = new DepartmentItem
                            {
                                Department = d
                            },
                            DepartmentSource = (from x in DB.md_Departments
                                                orderby x.OrderID
                                                select new SelectListItem
                                                {
                                                    Text = x.DepartmentLevel + x.DepartmentName,
                                                    Value = x.Guid,
                                                    Selected = (x.Guid == u.DepartmentGuid)
                                                }),
                            RoleList = (from rr in DB.md_RoleRelations
                                        from r in DB.md_Roles
                                        where rr.RoleGuid == r.Guid
                                        where rr.UserGuid == u.Guid
                                        orderby r.CreateTime
                                        select new SelectListItem
                                        {
                                            Text = r.RoleName,
                                            Value = r.Guid
                                        }).ToList()
                        }).ToList();               

                if (!U.HasRole(Role.MGR))
                {
                    List = List.Where(o => o.User.Guid == U.User.Guid).ToList();
                }
                else
                {
                    if (!String.IsNullOrEmpty(this.Query_UserName))
                        List = List.Where(o => o.User.UserName.Contains(this.Query_UserName)).ToList();

                    if (!String.IsNullOrEmpty(this.Query_DepartmentName))
                        List = List.Where(o => o.Department.Department.DepartmentName.Contains(this.Query_DepartmentName)).ToList();

                    if (!String.IsNullOrEmpty(this.Query_RoleName))
                        List = List.Where(o => o.RoleList.Count(n => n.Text.Contains(this.Query_RoleName)) > 0).ToList();

                    if (!Query_ShowAll)
                        List = List.Where(o => o.User.Status).ToList();

                    this.Row_Count = List.Count;

                    this.Page_Index = Math.Min((this.Row_Count - 1) / this.Page_Size, this.Page_Index);

                    List = List.Skip(this.Page_Index * this.Page_Size).Take(this.Page_Size).ToList();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return List;
        }

        private WebUserItem GetInsert()
        {
            WebUserItem One = new WebUserItem();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                One = new WebUserItem()
                {
                    DepartmentSource = (from x in DB.md_Departments
                                        orderby x.OrderID
                                        select new SelectListItem
                                        {
                                            Text = x.DepartmentLevel + x.DepartmentName,
                                            Value = x.Guid
                                        })
                };
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return One;
        }

        private IEnumerable<SelectListItem> GetRoleSource()
        {
            IEnumerable<SelectListItem> List = null;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = from r in DB.md_Roles
                       where r.Status
                       orderby r.CreateTime
                       select new SelectListItem()
                       {
                           Text = r.RoleName,
                           Value = r.Guid
                       };
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return List;
        }

        public String InsertItem(md_User Insert)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                if (String.IsNullOrEmpty(Insert.UserName.Trim()))
                    return "请输入“用户名”";

                if ((from x in DB.md_Users
                     where x.UserName == Insert.UserName
                     where x.DepartmentGuid == Insert.DepartmentGuid
                     select x).Any())
                {
                    return "该用户已存在";
                }

                if ((from x in DB.md_Users
                     where x.UserName == Insert.UserName
                     select x).Any())
                {
                    return "该用户名已在其他部门中存在，请确认";
                }

                IEnumerable<Int32> ieOrderID =
                    from x in DB.md_Users
                    select x.OrderID;

                Int32 intMaxOrderID = 0;

                if (ieOrderID.Any())
                    intMaxOrderID = ieOrderID.Max() + 1;

                Insert.Guid = Guid.NewGuid().ToString();

                DB.md_Users.InsertOnSubmit(
                    new md_User()
                    {
                        Guid = Insert.Guid,
                        UserName = Insert.UserName,
                        DepartmentGuid = Insert.DepartmentGuid,
                        OrderID = intMaxOrderID,
                        DisplayName = Insert.DisplayName,
                        Status = true,
                        Password = Insert.Password,
                    });

                IEnumerable<md_Department> ieDept = from x in DB.md_Departments
                                                    select x;

                String LogDes = String.Format("[新数据][用户名：{0}, 显示名：{2}, 组织：{1}]"
                    , Insert.UserName
                    , ieDept.Where(o => o.Guid == Insert.DepartmentGuid).First().DepartmentName
                    , Insert.DisplayName);


                String KeyDes = String.Format("[New][ UserName = '{0}' ,DisplayName = '{2}' ,DepartmentGuid = '{1}' ]"
                    , Insert.UserName
                    , Insert.DepartmentGuid
                    , Insert.DisplayName);


                CommonItem.WirteLog(DB, L_LogType.MD_User_Insert, LogDes, Insert.Guid, KeyDes, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_Insert, Ex, String.Format("[UserModel.InsertItem][参数：{0},{1},{2}]", Insert.UserName, Insert.DisplayName, Insert.DepartmentGuid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return "添加用户成功";
        }

        public String DeleteItem(String ID)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_User> ieSelf =
                    from x in DB.md_Users
                    where x.Guid == ID
                    select x;

                if (!ieSelf.Any())
                    return "用户不存在";

                String LogDes = String.Format("[原数据][用户名：{0}, 有效] => [新数据][用户名：{0}, 无效]", ieSelf.First().UserName);

                ieSelf.First().Status = false;

                CommonItem.WirteLog(DB, L_LogType.MD_User_Disable, LogDes, ieSelf.First().Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_Disable, Ex, String.Format("[UserModel.DeleteItem][参数：{0}]", ID), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return "用户删除成功";
        }

        public String EnableItem(String ID)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_User> ieSelf =
                    from x in DB.md_Users
                    where x.Guid == ID
                    select x;

                if (!ieSelf.Any())
                    return "用户不存在";

                String LogDes = String.Format("[原数据][用户名：{0}, 无效] => [新数据][用户名：{0}, 有效]", ieSelf.First().UserName);

                ieSelf.First().Status = true;

                CommonItem.WirteLog(DB, L_LogType.MD_User_Enable, LogDes, ieSelf.First().Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_Enable, Ex, String.Format("[UserModel.EnableItem][参数：{0}]", ID), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return "用户启用成功";
        }

        public DBOperationResult UpdateItem(md_User Update)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                IEnumerable<md_Department> ieDept = from x in DB.md_Departments
                                                   select x;

                //是否有记录可以被删除
                IEnumerable<md_User> ieSelf =
                    from x in DB.md_Users
                    where x.Guid == Update.Guid
                    select x;

                if (!ieSelf.Any())
                    return DBOperationResult.Update_Fail_NoRecord;

                String LogDes = String.Format("[原数据][用户名：{0}, 显示名：{4}, 组织：{1}] => [新数据][用户名：{2}, 显示名：{4}, 组织：{3}]"
                    , ieSelf.First().UserName
                    , ieDept.Where(o => o.Guid == ieSelf.First().DepartmentGuid).First().DepartmentName
                    , Update.UserName
                    , ieDept.Where(o => o.Guid == Update.DepartmentGuid).First().DepartmentName
                    , ieSelf.First().DisplayName
                    , Update.DisplayName);

                String KeyDes = String.Format("[Old][ UserName = '{0}' , DisplayName = '{4}' , DepartmentGuid = '{1}' ] => [New][ UserName = '{2}' , DisplayName = '{5}' , DepartmentGuid = '{3}' ]"
                    , ieSelf.First().UserName
                    , ieSelf.First().DepartmentGuid
                    , Update.UserName
                    , Update.DepartmentGuid
                    , ieSelf.First().DisplayName
                    , Update.DisplayName);

                ieSelf.First().UserName = Update.UserName;
                ieSelf.First().DepartmentGuid = Update.DepartmentGuid;
                ieSelf.First().DisplayName = Update.DisplayName;

                CommonItem.WirteLog(DB, L_LogType.MD_User_Update, LogDes, Update.Guid, KeyDes, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_Update, Ex, String.Format("[UserModel.UpdateItem][参数：{0},{1},{2}]", Update.UserName, Update.DisplayName, Update.DepartmentGuid), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return DBOperationResult.Update_Success;
        }

        public String ChangePwd(String UserID, String PwdOld, String PwdNew)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_User> ieSelf =
                    from x in DB.md_Users
                    where x.Password == PwdOld
                    where x.Guid == UserID
                    select x;

                if (!ieSelf.Any())
                    return "旧密码不正确";

                ieSelf.First().Password = PwdNew;

                CommonItem.WirteLog(DB, L_LogType.MD_User_ChangePwd, "[修改密码]", UserID, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_ChangePwd, Ex, String.Format("[UserModel.ChangePwd][参数：{0},{1}]", PwdOld, PwdNew), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return "修改密码成功";
        }

        public String ResetPwd(String UserID, String PwdNew)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                //是否有记录可以被删除
                IEnumerable<md_User> ieSelf =
                    from x in DB.md_Users
                    where x.Guid == UserID
                    select x;

                if (!ieSelf.Any())
                    return "用户不存在";

                ieSelf.First().Password = PwdNew;

                CommonItem.WirteLog(DB, L_LogType.MD_User_ResetPwd, "[重置密码]", UserID, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_User_ResetPwd, Ex, String.Format("[UserModel.ResetPwd][参数：{0}]", PwdNew), U);
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return "重置密码成功";
        }
    }

    #endregion

    #region Models.ExpenseCategory

    public class ExpenseCategoryModel:BaseModel
    {
        public ExpenseCategoryModel()
        {
            //Table = new List<ExpenseCategoryItem>();
            //Insert = new ExpenseCategoryItem();
            IsAll = false;
            ECList = new List<ExpenseCategoryItem>();
            EC = new ExpenseCategoryItem();
        }

        //public List<ExpenseCategoryItem> Table { get; set; }

        //public ExpenseCategoryItem Insert { get; set; }

        public Boolean IsAll { get; set; }

        public List<ExpenseCategoryItem> ECList { get; set; }

        public ExpenseCategoryItem EC { get; set; }

        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                this.ECList = (from c in DB.md_ExpenseCategories
                               from g in DB.md_ExpenseCategoryGroups
                               where c.ParentGuid == null
                               where c.CategoryGroup == g.CategoryGroup
                               where c.Status || this.IsAll
                               select new ExpenseCategoryItem
                               {
                                   Category = c,
                                   Group = g,
                                   GroupSource = from x in DB.md_ExpenseCategoryGroups
                                                 select new SelectListItem
                                                 {
                                                     Text = x.CategoryGroupName,
                                                     Value = x.CategoryGroup,
                                                     Selected = (x.CategoryGroup == c.CategoryGroup)
                                                 },
                                   ParentSource = from y in DB.md_ExpenseCategories
                                                  where false
                                                  select new SelectListItem
                                                  {
                                                      Text = y.CategoryName,
                                                      Value = y.CategoryGroup,
                                                  }
                               }).ToList();

                this.ECList.AddRange(from c in DB.md_ExpenseCategories
                                     from p in DB.md_ExpenseCategories
                                     from g in DB.md_ExpenseCategoryGroups
                                     where c.ParentGuid == p.Guid
                                     where c.CategoryGroup == g.CategoryGroup
                                     where c.Status || this.IsAll
                                     select new ExpenseCategoryItem
                                     {
                                         Category = c,
                                         Group = g,
                                         Parent = p,
                                         GroupSource = from x in DB.md_ExpenseCategoryGroups
                                                       select new SelectListItem
                                                       {
                                                           Text = x.CategoryGroupName,
                                                           Value = x.CategoryGroup,
                                                           Selected = (x.CategoryGroup == c.CategoryGroup)
                                                       },
                                         ParentSource = from y in DB.md_ExpenseCategories
                                                        from z in DB.md_ExpenseCategories
                                                        where y.Status
                                                        where y.CategoryGroup == z.CategoryGroup
                                                        where z.Guid == c.ParentGuid
                                                        orderby y.OrderID
                                                        select new SelectListItem
                                                        {
                                                            Text = y.CategoryName,
                                                            Value = y.CategoryGroup,
                                                            Selected = (y.Guid == c.ParentGuid)
                                                        }
                                     });

                this.ECList = this.ECList.OrderBy(o => o.Category.OrderID).ToList();

                this.EC = new ExpenseCategoryItem()
                {
                    GroupSource = (from x in DB.md_ExpenseCategoryGroups
                                   select new SelectListItem
                                   {
                                       Text = x.CategoryGroupName,
                                       Value = x.CategoryGroup
                                   }),
                    ParentSource = (from y in DB.md_ExpenseCategories
                                    where false
                                    select new SelectListItem
                                    {
                                        Text = y.CategoryName,
                                        Value = y.Guid
                                    })
                };
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }
        }

        public String InsertItem(md_ExpenseCategory Insert)
        {
            if (Insert.CategoryName.Trim() == String.Empty)
                return "费用科目不能为空";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                if ((from x in DB.md_ExpenseCategories where x.CategoryName == Insert.CategoryName select x).Any())
                    return "该费用科目已存在";

                if (Insert.CategoryGroup != String.Empty && Insert.ParentGuid == String.Empty)
                    return "2级科目需要设置父科目";

                int iMaxOrderID = 0;
                int iMaxOrderIDInP = 0;

                List<int> ieOrderID = (from x in DB.md_ExpenseCategories select x.OrderID).ToList();
                List<int> ieOrderIDInP = (from x in DB.md_ExpenseCategories where x.ParentGuid == Insert.ParentGuid select x.OrderID).ToList();
                ieOrderIDInP.AddRange(from x in DB.md_ExpenseCategories where x.Guid == Insert.ParentGuid select x.OrderID);

                if (ieOrderID.Any()) { iMaxOrderID = ieOrderID.Max(); }
                if (ieOrderIDInP.Any())
                    iMaxOrderIDInP = ieOrderIDInP.Max();
                else
                    iMaxOrderIDInP = iMaxOrderID;

                if (iMaxOrderID != iMaxOrderIDInP)
                {
                    List<md_ExpenseCategory> lsNext = (
                        from x in DB.md_ExpenseCategories
                        where (x.OrderID > iMaxOrderIDInP)
                        select x).ToList();

                    foreach (md_ExpenseCategory oNext in lsNext)
                        oNext.OrderID = oNext.OrderID + 1;
                }

                Insert = new md_ExpenseCategory()
                {
                    Guid = Guid.NewGuid().ToString(),
                    CategoryName = Insert.CategoryName,
                    CategoryGroup = Insert.CategoryGroup,
                    ParentGuid = Insert.ParentGuid,
                    Status = true,
                    OrderID = Math.Min(iMaxOrderID, iMaxOrderIDInP) + 1,
                    HasChid = Insert.HasChid,
                };

                DB.md_ExpenseCategories.InsertOnSubmit(Insert);

                String LogDes = String.Format("[新数据][费用科目：{0}]", Insert.CategoryName);

                String KeyDes = String.Format("[New][ Guid = '{0}', CategoryName = '{1}', CategoryGroup = '{2}', ParentGuid = '{3}', HasChid = '{4}', OrderID = '{5}' ]"
                    , Insert.Guid
                    , Insert.CategoryName
                    , Insert.CategoryGroup
                    , Insert.ParentGuid
                    , Insert.HasChid
                    , Insert.OrderID);

                CommonItem.WirteLog(DB, L_LogType.MD_ExpenseCategory_Insert, LogDes, Insert.Guid, KeyDes, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                return "科目新建成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_ExpenseCategory_Insert, Ex
                    , String.Format("[ExpenseCategoryModel.InsertItem][参数：{0},{1},{2},{3}]", Insert.CategoryName, Insert.CategoryGroup, Insert.ParentGuid, Insert.HasChid)
                    , U);

                return "科目新建失败";
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public String UpdateItem(md_ExpenseCategory Update)
        {
            if (Update.CategoryName.Trim() == String.Empty)
                return "费用科目不能为空";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                if ((from x in DB.md_ExpenseCategories
                     where x.CategoryName == Update.CategoryName 
                     where x.Guid != Update.Guid
                     where x.ParentGuid == Update.ParentGuid
                     select x).Any())
                    return "该费用科目已存在";

                if (Update.CategoryGroup != String.Empty && Update.ParentGuid == String.Empty)
                    return "2级科目需要设置父科目";

                IEnumerable<md_ExpenseCategory> ieOld = from x in DB.md_ExpenseCategories
                                                        where x.Guid == Update.Guid
                                                        select x;

                if(!ieOld.Any())
                    return "费用科目修改失败";

                md_ExpenseCategory Old = ieOld.First();

                List<md_ExpenseCategoryGroup> Group = (from x in DB.md_ExpenseCategoryGroups select x).ToList();
                List<md_ExpenseCategory> Parent = (from x in DB.md_ExpenseCategories select x).ToList();

                String LogDes = String.Format("[原数据][费用科目：{0}, 层级：{1}, 父科目：{2}，允许三级科目：{3}] => [新数据][费用科目：{4}, 层级：{5}, 父科目：{6}，允许三级科目：{7}]"
                    , Old.CategoryName
                    , Group.Where(o => o.CategoryGroup == Old.CategoryGroup).First().CategoryGroupName
                    , Parent.Where(o => o.Guid == Old.ParentGuid).First().CategoryName
                    , Old.HasChid ? "是" : "否"
                    , Update.CategoryName
                    , Group.Where(o => o.CategoryGroup == Update.CategoryGroup).First().CategoryGroupName
                    , Parent.Where(o => o.Guid == Update.ParentGuid).First().CategoryName
                    , Update.HasChid ? "是" : "否");

                String KeyDes = String.Format("[Old][CategoryName：{0}, CategoryGroup：{1}, ParentGuid：{2}，HasChid：{3}] => [New][CategoryName：{4}, CategoryGroup：{5}, ParentGuid：{6}，HasChid：{7}]"
                    , Old.CategoryName
                    , Old.CategoryGroup
                    , Old.ParentGuid
                    , Old.HasChid
                    , Update.CategoryName
                    , Update.CategoryGroup
                    , Update.ParentGuid
                    , Update.HasChid);

                if (Old.ParentGuid == Update.ParentGuid)
                {
                    Old.CategoryName = Update.CategoryName;
                    Old.HasChid = Update.HasChid;
                }
                else
                {
                    DB.md_ExpenseCategories.DeleteOnSubmit(Old);

                    int iMaxOrderID = 0;
                    int iMaxOrderIDInP = 0;

                    List<int> ieOrderID = (from x in DB.md_ExpenseCategories select x.OrderID).ToList();
                    List<int> ieOrderIDInP = (from x in DB.md_ExpenseCategories where x.ParentGuid == Update.ParentGuid select x.OrderID).ToList();
                    ieOrderIDInP.AddRange(from x in DB.md_ExpenseCategories where x.Guid == Update.ParentGuid select x.OrderID);

                    if (ieOrderID.Any()) { iMaxOrderID = ieOrderID.Max(); }
                    if (ieOrderIDInP.Any())
                        iMaxOrderIDInP = ieOrderIDInP.Max();
                    else
                        iMaxOrderIDInP = iMaxOrderID;

                    if (iMaxOrderID != iMaxOrderIDInP)
                    {
                        List<md_ExpenseCategory> lsNext = (
                            from x in DB.md_ExpenseCategories
                            where (x.OrderID > iMaxOrderIDInP)
                            select x).ToList();

                        foreach (md_ExpenseCategory oNext in lsNext)
                            oNext.OrderID = oNext.OrderID + 1;
                    }

                    Update = new md_ExpenseCategory()
                    {
                        Guid = Update.Guid,
                        CategoryName = Update.CategoryName,
                        CategoryGroup = Update.CategoryGroup,
                        ParentGuid = Update.ParentGuid,
                        Status = Old.Status,
                        OrderID = Math.Min(iMaxOrderID, iMaxOrderIDInP) + 1,
                        HasChid = Update.HasChid,
                    };

                    DB.md_ExpenseCategories.InsertOnSubmit(Update);
                }

                CommonItem.WirteLog(DB, L_LogType.MD_ExpenseCategory_Update, LogDes, Update.Guid, KeyDes, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                return "费用科目修改成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_ExpenseCategory_Update, Ex, String.Format("[ExpenseCategoryModel.UpdateItem][参数：{0},{1},{2},{3},{4}]", Update.Guid, Update.CategoryName, Update.CategoryGroup, Update.ParentGuid, Update.HasChid), U);

                return "费用科目修改失败";
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public String DisableItem(md_ExpenseCategory Disable)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                IEnumerable<md_ExpenseCategory> ieDisable = from x in DB.md_ExpenseCategories
                                                        where x.Guid == Disable.Guid
                                                        select x;

                if (!ieDisable.Any())
                    return "费用科目删除失败";

                ieDisable.First().Status = false;

                IEnumerable<md_ExpenseCategory> ieChild = from x in DB.md_ExpenseCategories
                                                              where x.ParentGuid == Disable.Guid
                                                              select x;

                if (ieChild.Any())
                {
                    List<md_ExpenseCategory> lsChild = ieChild.ToList();
                    foreach (md_ExpenseCategory aChild in lsChild)
                        aChild.Status = false;
                }

                String LogDes = String.Format("[原数据][费用科目：{0} 有效] => [新数据][费用科目：{0} 无效]", Disable.CategoryName);

                CommonItem.WirteLog(DB, L_LogType.MD_ExpenseCategory_Disable, LogDes, Disable.Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                return "费用科目删除成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_ExpenseCategory_Disable, Ex, String.Format("[ExpenseCategoryModel.DisableItem][参数：{0}]", Disable.Guid), U);

                return "费用科目修改失败";
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public String EnableItem(md_ExpenseCategory Disable)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                IEnumerable<md_ExpenseCategory> ieDisable = from x in DB.md_ExpenseCategories
                                                            where x.Guid == Disable.Guid
                                                            select x;

                if (!ieDisable.Any())
                    return "费用科目启用失败";

                ieDisable.First().Status = true;

                IEnumerable<md_ExpenseCategory> ieParent = from x in DB.md_ExpenseCategories
                                                           where x.Guid == ieDisable.First().ParentGuid
                                                           where !x.Status
                                                           select x;

                if (ieParent.Any())
                    ieParent.First().Status = true;

                String LogDes = String.Format("[原数据][费用科目：{0} 无效] => [新数据][费用科目：{0} 有效]", Disable.CategoryName);

                CommonItem.WirteLog(DB, L_LogType.MD_ExpenseCategory_Enable, LogDes, Disable.Guid, String.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                return "费用科目启用成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.MD_ExpenseCategory_Enable, Ex, String.Format("[ExpenseCategoryModel.EnableItem][参数：{0}]", Disable.Guid), U);

                return "费用科目启用失败";
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public static List<SelectListItem> GetParent(String Group)
        {
            List<SelectListItem> List = new List<SelectListItem>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = (
                    from g in DB.md_ExpenseCategoryGroups
                    from pg in DB.md_ExpenseCategoryGroups
                    from p in DB.md_ExpenseCategories
                    orderby p.OrderID ascending
                    where g.CategoryGroup == Group
                    where pg.OrderID == (g.OrderID - 1)
                    where p.CategoryGroup == pg.CategoryGroup                   
                    select new SelectListItem { Text = p.CategoryName, Value = p.Guid }).ToList();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB.Dispose();
                DB = null;
            }

            return List;
        }
    }

    #endregion

    #region Models.Role

    public class RoleModel : BaseModel
    {
        public RoleModel()
        {
            Insert = new RoleItem();
            Update = new RoleItem();
            Table = new List<RoleItem>();
            AllPage = new List<md_Page>();
            PageString = String.Empty;
        }

        public String PageString { get; set; }

        public List<md_Page> AllPage { get; set; }

        public RoleItem Insert { get; set; }

        public RoleItem Update { get; set; }

        public List<RoleItem> Table { get; set; }

        public static RoleItem GetInsert()
        {
            RoleItem One = new RoleItem();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List<SelectListItem> lsDeprtment = (
                                from x in DB.md_Departments
                                orderby x.OrderID
                                select new SelectListItem()
                                {
                                    Text = x.DepartmentLevel + x.DepartmentName,
                                    Value = x.Guid
                                }).ToList();

                List<SelectListItem> lsPjCategory = (
                    from x in DB.list_ProjectCategories
                    where x.Name != ""
                    orderby x.ID
                    select new SelectListItem()
                    {
                        Text = x.Name,
                        Value = x.ID
                    }).ToList();

                lsDeprtment.Insert(0, new SelectListItem() { Text = "全部门", Value = ((int)L_SubRoleType.AllDepartment).ToString() });
                lsDeprtment.Insert(1, new SelectListItem() { Text = "本部门", Value = ((int)L_SubRoleType.SelfDepartment).ToString() });
                lsDeprtment.Insert(2, new SelectListItem() { Text = "本人", Value = ((int)L_SubRoleType.Self).ToString() });

                lsPjCategory.Insert(0, new SelectListItem() { Text = "全部", Value = "" });
                One = new RoleItem()
                {
                    RoleList = new List<SubRoleItem>()
                    {
                        new SubRoleItem(){
                             DepartmentSource = lsDeprtment,
                             ProjectCtegorySource = lsPjCategory
                        }
                    }
                };

                
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }

            return One;
        }

        public void GetDetail(String ID)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                this.Update.Role = (
                    from x in DB.md_Roles
                    where x.Guid == ID
                    select x).First();

                IEnumerable<md_Page> iePage = from p in DB.md_Pages
                                              from rp in DB.md_RolePages
                                              where p.PageID == rp.PageID
                                              where rp.RoleGuid == ID
                                              select p;

                if (iePage.Any())
                {
                    foreach (md_Page oPage in iePage.ToList())
                    {
                        this.PageString = this.PageString + oPage.PageID + ";";
                    }
                }

                List<md_SubRole> lsItem = (
                    from sub in DB.md_SubRoles
                    where sub.RoleGuid == ID
                    orderby sub.OrderID
                    select sub).ToList();

                for (int i = 0; i < lsItem.Count; i++)
                {
                    String[] arryAuth = lsItem[i].AuthorityString.Split('-');

                    List<SelectListItem> lsDeprtment = (from x in DB.md_Departments
                                                        orderby x.OrderID
                                                        select new SelectListItem()
                                                        {
                                                            Text = x.DepartmentLevel + x.DepartmentName,
                                                            Value = x.Guid
                                                        }).ToList();

                    List<SelectListItem> lsPjCategory = (from x in DB.list_ProjectCategories
                                                         where x.Name != ""
                                                         orderby x.ID
                                                         select new SelectListItem()
                                                         {
                                                             Text = x.Name,
                                                             Value = x.ID
                                                         }).ToList();

                    lsDeprtment.Insert(0, new SelectListItem() { Text = "全部门", Value = ((int)L_SubRoleType.AllDepartment).ToString() });
                    lsDeprtment.Insert(1, new SelectListItem() { Text = "本部门", Value = ((int)L_SubRoleType.SelfDepartment).ToString() });
                    lsDeprtment.Insert(2, new SelectListItem() { Text = "本人", Value = ((int)L_SubRoleType.Self).ToString() });

                    lsPjCategory.Insert(0, new SelectListItem() { Text = "全部", Value = "" });

                    SubRoleItem SR = new SubRoleItem()
                    {
                        Department = new md_Department() { Guid = lsItem[i].DepartmentGuid },
                        DepartmentSource = lsDeprtment,
                        ProjectCtegory = new list_ProjectCategory() { ID = lsItem[i].ProjectCategoryID },
                        ProjectCtegorySource = lsPjCategory,
                        Type = (L_SubRoleType)lsItem[i].Type,
                        OpenAuth = new SubRole_Open(arryAuth[0]),
                        UploadAuth = new SubRole_Upload(arryAuth[1]),
                        AuditAuth = new SubRole_Approve(arryAuth[2]),
                        InUseAuth = new SubRole_Use(arryAuth[3]),
                        AdjustAuth = new SubRole_Adjust(arryAuth[4]),
                        CompleteAuth = new SubRole_Complete(arryAuth[5]),
                        CloseAuth = new SubRole_Close(arryAuth[6]),
                        HistoryAuth = new SubRole_History(arryAuth[7]),
                        OrderID = lsItem[i].OrderID,
                    };

                    SR.ProjectCtegorySource.Where(o => o.Value == SR.ProjectCtegory.ID).First().Selected = true;
                    switch (SR.Type)
                    {
                        case L_SubRoleType.Department:
                            SR.DepartmentSource.Where(o => o.Value == SR.Department.Guid).First().Selected = true;
                            break;
                        case L_SubRoleType.AllDepartment:
                        case L_SubRoleType.SelfDepartment:
                        case L_SubRoleType.Self:
                            SR.DepartmentSource.Where(o => o.Value == ((int)SR.Type).ToString()).First().Selected = true;
                            break;
                    }

                    this.Update.RoleList.Add(SR);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public static void InsertItem(RoleItem Insert)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                String RoleGuid = Guid.NewGuid().ToString();

                DB.md_Roles.InsertOnSubmit(
                    new md_Role()
                    {
                        Guid = RoleGuid,
                        RoleName = Insert.Role.RoleName,
                        RoleDescription = Insert.Role.RoleDescription,
                        Status = true,
                        CreateTime = DateTime.Now
                    });

                int Index = 0;
                
                foreach(SubRoleItem SR in Insert.RoleList)
                {
                    DB.md_SubRoles.InsertOnSubmit(
                        new md_SubRole()
                        {
                            AuthorityString = String.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}"
                                                    , SR.OpenAuth.ToString()
                                                    , SR.UploadAuth.ToString()
                                                    , SR.AuditAuth.ToString()
                                                    , SR.InUseAuth.ToString()
                                                    , SR.AdjustAuth.ToString()
                                                    , SR.CompleteAuth.ToString()
                                                    , SR.CloseAuth.ToString()
                                                    , SR.HistoryAuth.ToString()),
                            Guid = Guid.NewGuid().ToString(),
                            DepartmentGuid = (SR.Type == L_SubRoleType.Department) ? SR.Department.Guid : "",
                            RoleGuid = RoleGuid,
                            Type = (int)SR.Type,
                            ProjectCategoryID = SR.ProjectCtegory.ID,
                            OrderID = Index++,
                        });
                }

                IEnumerable<md_RolePage> ieRP = from ls in Insert.PageList
                                                select new md_RolePage()
                                                {
                                                    PageID = ls.ToString(),
                                                    RoleGuid = Insert.Role.Guid
                                                };

                if (ieRP.Any())
                    DB.md_RolePages.InsertAllOnSubmit(ieRP);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception)
            {
                DB.Transaction.Rollback();
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public static void UpdateItem(RoleItem Update)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                md_Role oRole = (from x in DB.md_Roles
                                 where x.Guid == Update.Role.Guid
                                 select x).First();

                oRole.RoleName = Update.Role.RoleName;
                oRole.RoleDescription = Update.Role.RoleDescription;

                DB.md_SubRoles.DeleteAllOnSubmit(
                    from x in DB.md_SubRoles
                    where x.RoleGuid == Update.Role.Guid
                    select x);

                int Index = 0;

                foreach (SubRoleItem SR in Update.RoleList)
                {
                    DB.md_SubRoles.InsertOnSubmit(
                        new md_SubRole()
                        {
                            AuthorityString = String.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}"
                                                    , SR.OpenAuth.ToString()
                                                    , SR.UploadAuth.ToString()
                                                    , SR.AuditAuth.ToString()
                                                    , SR.InUseAuth.ToString()
                                                    , SR.AdjustAuth.ToString()
                                                    , SR.CompleteAuth.ToString()
                                                    , SR.CloseAuth.ToString()
                                                    , SR.HistoryAuth.ToString()),
                            Guid = Guid.NewGuid().ToString(),
                            DepartmentGuid = (SR.Type == L_SubRoleType.Department) ? SR.Department.Guid : "",
                            RoleGuid = oRole.Guid,
                            Type = (int)SR.Type,
                            ProjectCategoryID = SR.ProjectCtegory.ID,
                            OrderID = Index++,
                        });
                }

                IEnumerable<md_RolePage> ieRP_O = from rp in DB.md_RolePages
                                                where rp.RoleGuid == Update.Role.Guid
                                                select rp;
                if (ieRP_O.Any())
                    DB.md_RolePages.DeleteAllOnSubmit(ieRP_O);

                IEnumerable<md_RolePage> ieRP_N = from ls in Update.PageList
                                                  select new md_RolePage()
                                                  {
                                                      PageID = ls.ToString(),
                                                      RoleGuid = Update.Role.Guid
                                                  };

                if (ieRP_N.Any())
                    DB.md_RolePages.InsertAllOnSubmit(ieRP_N);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception)
            {
                DB.Transaction.Rollback();
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public static void DeleteItem(String ID)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                DB.md_Roles.DeleteAllOnSubmit(
                    from x in DB.md_Roles
                    where x.Guid == ID
                    select x);

                DB.md_SubRoles.DeleteAllOnSubmit(
                    from x in DB.md_SubRoles
                    where x.RoleGuid == ID
                    select x);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception)
            {
                DB.Transaction.Rollback();
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }

        public void GetTable()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                this.Table= (from r in DB.md_Roles
                        where r.Status
                        orderby r.CreateTime
                        select new RoleItem
                        {
                            Role = r
                        }).ToList();

                this.AllPage = (from p in DB.md_Pages
                                orderby p.PageID
                                select p).ToList();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }
        }
    }

    #endregion

    #region Models.RoleRelation

    public class RoleRelationModel : BaseModel
    {
        public RoleRelationModel()
        {
            Insert = new RoleRelationItem();
            Update = new RoleRelationItem();
            Table = new List<RoleRelationItem>();
        }

        public RoleRelationItem Insert { get; set; }

        public RoleRelationItem Update { get; set; }

        public IEnumerable<SelectListItem> RoleSource { get; set; }

        public List<RoleRelationItem> Table { get; set; }

        public static IEnumerable<SelectListItem> GetRoleSource()
        {
            IEnumerable<SelectListItem> List = null;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = from r in DB.md_Roles
                       where r.Status
                       orderby r.CreateTime
                       select new SelectListItem()
                       {
                           Text = r.RoleName,
                           Value = r.Guid
                       };
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return List;
        }

        public static List<RoleRelationItem> GetTable()
        {
            List<RoleRelationItem> List = new List<RoleRelationItem>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = (from u in DB.md_Users
                        from d in DB.md_Departments
                        where u.DepartmentGuid == d.Guid
                        where u.Status
                        orderby u.OrderID
                        select new RoleRelationItem
                        {
                            User = new UserItem()
                            {
                                User = u,
                                Department = new DepartmentItem()
                                {
                                     Department = d
                                }
                            },
                            RoleList =
                            (from rr in DB.md_RoleRelations
                             from r in DB.md_Roles
                             where rr.RoleGuid == r.Guid
                             where rr.UserGuid == u.Guid
                             orderby r.CreateTime
                             select new SelectListItem
                             {
                                 Text = r.RoleName,
                                 Value = r.Guid
                             }).ToList()
                        }).ToList();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return List;
        }

        public static RoleRelationItem GetDetail(String ID)
        {
            RoleRelationItem One = new RoleRelationItem();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                One = (from u in DB.md_Users
                       from d in DB.md_Departments
                       where u.DepartmentGuid == d.Guid
                       where u.Guid == ID
                       orderby u.OrderID
                       select new RoleRelationItem
                       {
                           User = new UserItem(){
                            User = u,
                             Department = new DepartmentItem(){
                              Department = d
                             }
                           },
                           RoleList =
                           (from rr in DB.md_RoleRelations
                            from r in DB.md_Roles
                            where rr.RoleGuid == r.Guid
                            where rr.UserGuid == u.Guid
                            orderby r.CreateTime
                            select new SelectListItem
                            {
                                Text = r.RoleName,
                                Value = r.Guid
                            }).ToList()
                       }).First();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return One;
        }

        public static void UpdateItem(RoleRelationItem Update)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                DB.md_RoleRelations.DeleteAllOnSubmit(
                    from rr in DB.md_RoleRelations
                    where rr.UserGuid == Update.User.User.Guid
                    select rr);

                foreach (SelectListItem Role in Update.RoleList)
                {
                    DB.md_RoleRelations.InsertOnSubmit(
                        new md_RoleRelation()
                        {
                            UserGuid = Update.User.User.Guid,
                            RoleGuid = Role.Value
                        });
                }

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception)
            {
                DB.Transaction.Rollback();
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }
    }

    #endregion

    #region Models.Project

    public class ProjectModel:BaseModel
    {
        public ProjectModel()
        {
            Table = new List<ProjectItem>();

            PjCategorySource = new List<SelectListItem>();
            PjType = new List<SelectListItem>();
            BS = new List<list_BudgetStatus>();

            Q_Department = String.Empty;
            Q_PIC = String.Empty;
            Q_PjCategory = String.Empty;
            Q_PjCode = String.Empty;
            Q_PjName = String.Empty;
            Q_PjType = String.Empty;
            Q_ShowNoRelation = false;
        }

        public List<ProjectItem> Table { get; set; }

        public List<list_BudgetStatus> BS { get; set; }

        public String Q_PjCategory { get; set; }

        public String Q_PjType { get; set; }

        public String Q_Department { get; set; }

        public String Q_PIC { get; set; }

        public String Q_PjName { get; set; }

        public String Q_PjCode { get; set; }

        public Boolean Q_ShowNoRelation { get; set; }

        public List<SelectListItem> PjCategorySource { get; set; }

        public List<SelectListItem> PjType { get; set; }

        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                IEnumerable<SelectListItem> ieTmpPjC = (from x in DB.list_ProjectCategories
                                                        select new SelectListItem() { Text = x.Name, Value = x.ID });
                if (ieTmpPjC.Any())
                    this.PjCategorySource = ieTmpPjC.ToList();
                //this.PjCategorySource.Insert(0, new SelectListItem());

                IEnumerable<SelectListItem> ieTmpPjT = (from x in DB.list_ProjcetTypes
                                                        select new SelectListItem() { Text = x.Name, Value = x.ID });
                if (ieTmpPjT.Any())
                    this.PjType = ieTmpPjT.ToList();
                //this.PjType.Insert(0, new SelectListItem());

                IEnumerable<list_BudgetStatus> ieTmpBS = from x in DB.list_BudgetStatus select x;
                if (ieTmpBS.Any()) { this.BS = ieTmpBS.ToList(); }
            
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }
        }

        public void Query()
        {
            IEnumerable<ProjectItem> List = new List<ProjectItem>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                List = (from p in DB.md_Projects
                        from c in DB.list_ProjectCategories
                        from t in DB.list_ProjcetTypes
                        from d in DB.md_Departments
                        from u in DB.md_Users
                        where u.Guid == p.ProjectPIC
                        where p.ProjectCategoryID == c.ID
                        where p.ProjectTypeID == t.ID
                        where p.DepartmentGuid == d.Guid
                        where (String.IsNullOrEmpty(this.Q_PjCategory) || this.Q_PjCategory == "0" || this.Q_PjCategory == p.ProjectCategoryID)
                        where (String.IsNullOrEmpty(this.Q_PjType) || this.Q_PjType == p.ProjectTypeID)
                        where (String.IsNullOrEmpty(this.Q_Department) || d.DepartmentName.Contains(this.Q_Department))
                        where (String.IsNullOrEmpty(this.Q_PIC) || u.UserName.Contains(this.Q_PIC))
                        where (String.IsNullOrEmpty(this.Q_PjName) || p.ProjectName.Contains(this.Q_PjName))
                        where (String.IsNullOrEmpty(this.Q_PjCode) || p.ProjectCode.Contains(this.Q_PjCode))
                        orderby p.CreateTime
                        select new ProjectItem()
                        {
                            Project = p,
                            ProjectCategory = c,
                            ProjcetType = t,
                            Department = d,
                            Budget = (from x in DB.wf_Budgets
                                      where x.ProjectGuid == p.Guid
                                      select x),
                        });

                if (this.Q_ShowNoRelation)
                {
                    List = from x in List
                           where (!x.Budget.Any())
                           select x;
                }

                this.Row_Count = List.Count();
                this.Page_Index = Math.Min((this.Row_Count - 1) / this.Page_Size, this.Page_Index);

                if (List.Any())
                    this.Table = List.Skip(this.Page_Index * this.Page_Size).Take(this.Page_Size).ToList();
            }
            catch (Exception)
            {
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }
        }
        
        public void DeleteItem(String ID)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            try
            {
                //是否有记录可以被删除

                IEnumerable<md_Project> ieSelf = from x in DB.md_Projects
                                                 where x.Guid == ID
                                                 select x;

                if (ieSelf.Any())
                {
                    String LogDes = String.Format("[删除数据][项目代号：{0}, 项目名称：{1}]", ieSelf.First().ProjectCode, ieSelf.First().ProjectName);

                    DB.md_Projects.DeleteAllOnSubmit(ieSelf);

                    CommonItem.WirteLog(DB, L_LogType.MD_Project_Delete, LogDes, ieSelf.First().Guid, String.Empty, this.U);
                }

                DB.SubmitChanges();
            }
            catch (Exception Ex)
            {
                CommonItem.WirteErrorLog(L_LogType.MD_Project_Delete, Ex, String.Format("[ProjectModel.DeleteItem][参数：{0}]", ID), this.U);
                throw Ex;
            }
            finally
            {
                DB.Connection.Close();
                //DB.Dispose();
                DB = null;
            }
        }
    }

    #endregion
}
